【问题标题】:How to override delegated attribute in factory_girl?如何覆盖 factory_girl 中的委托属性?
【发布时间】:2016-09-04 09:09:06
【问题描述】:

我有一个委托给关联对象(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')

它根本不起作用,并且该属性正在按默认顺序设置。

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

【问题讨论】:

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


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 2015-06-20
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 2014-08-18
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多