如何覆盖factory_girl中的委托属性?

时间:2016-05-09 16:21:12

标签: ruby-on-rails ruby postgresql rspec factory-bot

我有一个委托给关联对象(AR / Postgres)的属性,并且在调用工厂时试图覆盖它。

class Patient
    delegate :email, to: :credential
    has_one :credential, as: :owner,  dependent: :destroy
end

class Credential
    belongs_to :owner, polymorphic: true
end

FactoryGirl.define do
  factory :patient do
    first_name 'Jane'
    last_name 'Patient'
    dob Date.parse('2005-01-11')
    gender 'Female'
    zipcode '80202'

    after(:build) do |user|
      create(:credential, owner: user)
    end
  end
end

FactoryGirl.define do
  factory :credential do
    password '!Secret15'
    password_confirmation { password }
    agree_to_terms true

    sequence :email do |n|
     "user#{n}@bar.com"
    end
  end
end

电话:

create(:patient, email: 'new@email.com')

它根本不起作用,属性由默认序列设置。

搜索他们的文档和谷歌,但找不到答案。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

factory_girl对delegate没有做任何事情。您需要自己将email传递给:credential工厂。属性在回调中不可用,因此从评估器获取email,这是回调块的第二个参数:

FactoryGirl.define do
  factory :patient do
    # other attributes

    after(:build) do |user, evaluator|
      create(:credential, owner: user, email: evaluator.email)
    end
  end
end

此处记录:https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#transient-attributes