我有以下工厂:
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
答案 0 :(得分:2)
重新:检查已设置的值。
f.after_build do |obj|
# Test your obj.membership here.
end
Re:错误消息抱怨after_build
不存在。
您的定义语法会显示出来。改变这个:
FactoryGirl.define do
factory :group_member do |f|
到此:
FactoryGirl.define :group_member do |f|