2

我有以下工厂:

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
4

1 回答 1

2

回复:检查已设置的值。

f.after_build do |obj|   
  # Test your obj.membership here. 
end

回复:抱怨after_build不存在的错误消息。

您的定义语法看起来不正确。改变这个:

FactoryGirl.define do
  factory :group_member do |f|

对此:

FactoryGirl.define :group_member do |f|
于 2013-01-17T16:32:06.030 回答