我有以下工厂:
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
该行:
if "#{membership}" == "accepted"
正在抛出错误:
Trait not registered: membership
我的目的是查明先前定义的特征“成员资格”是否设置为“接受”。但是,我不确定如何访问该特征。有小费吗?
另一方面,工厂创建类似于表单创建,只要有一个变量(在本例中为“f”)分配了各种特征。有没有一个词来描述这些类型的代码块?
更新:我已将工厂更改为使用 after_build 调用,但现在出现此错误:
undefined method `after_build=' for #<GroupMember:0x5dcb328>
更新后的代码如下所示:
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