Reputation: 8189
I have the following factory:
FactoryGirl.define do
factory :group_member do |f|
f.user_id { rand(1..100) }
f.group_id { rand(1..100) }
f.membership { ["accepted", "invited", "declined", "requested", "denied", "left", "removed"].sample }
if "#{membership}" == "accepted"
f.host { [true, false].sample }
else
f.host false
end
end
end
The line:
if "#{membership}" == "accepted"
is throwing the error:
Trait not registered: membership
My intention is to find out if the previously defined trait "membership" is set to "accepted." I'm not sure how to access that trait, however. Any tips?
On another note, factory creation resembles form creation, in so far as there's a variable ('f' in this case) which is assigned various traits. Is there a word to describe these types of code blocks?
UPDATE: I've changed the factory to use an after_build call, but now I'm getting this error:
undefined method `after_build=' for #<GroupMember:0x5dcb328>
The updated code looks like:
FactoryGirl.define do
factory :group_member do |f|
f.user_id { rand(1..100) }
f.group_id { rand(1..100) }
f.membership { ["accepted", "invited", "declined", "requested", "denied", "left", "removed"].sample }
f.after_build do |obj|
if obj.membership == "accepted"
obj.host = [true, false].sample
else
obj.host = false
end
end
end
end
Upvotes: 3
Views: 147
Reputation: 17790
Re: Checking values already set.
f.after_build do |obj|
# Test your obj.membership here.
end
Re: The error message complaining that after_build
doesn't exist.
Your definition syntax looks off. Change this:
FactoryGirl.define do
factory :group_member do |f|
to this:
FactoryGirl.define :group_member do |f|
Upvotes: 2