Transient attributes in Factory Girl
We are preferring Factory Girl
Gem to simulate the application related test data.
What is Factory Girl?
A library for setting up Ruby objects as test data, a replacement for Fixtures.
Factories allow you to create valid instances of your Rails model classes to reuse. Factories are commonly used to DRY
out unit tests.
Transient Attributes
- Customize your factory behaviour with fake/virtual attributes.
- These attributes are just parameters to the factory method call that can be used by your code inside the factory.
Now, let’s see the following example.
factory :post do
transient do
approved false
end
title { approved ? "This is my first post" : "Admin, please approve this post" }
end
create(:post).title
#=> "Admin, please approve this post"
create(:post, approved: true).title
#=> "This is my first post"
In the above example, approved
is a fake/virtual attribute which does not belong to Post
model & we are creating title of the Post on the basis of this transient attribute’s value.
Note: In the older versions, it is also known as ignored attributes
. The old ignore
syntax has been deprecated and removed from Factory Girl version 3.0 onwards.