【问题标题】:FactoryGirl and getting an attribute-hash with all associationsFactoryGirl 并获取所有关联的属性哈希
【发布时间】:2013-12-22 13:12:31
【问题描述】:

我有两个相关的模型 - Customer,其中有一个 Address。这些是我的工厂:

FactoryGirl.define do
  factory :customer do
    address
  end
end

FactoryGirl.define do
  factory :address do
    company_name "MyString"
    …
  end
end

在我的控制器规范中,我尝试为客户获取包含地址属性的哈希值……这对我不起作用。

第一次尝试是使用attributes_for(:customer),但这会忽略任何关联(如文档中所述)。在谷歌搜索后,我发现了使用FactoryGirl.build(:customer).attributes.symbolize_keys 的建议,其中应该包括关联参数。但不适合我,我只是得到{"id"=>…, "created_at"=>…, "updated_at"=>…}。但是customer.address.attributes 输出了正确的哈希,所以关联似乎是正确的。

所以,我有一个正确的客户和一个有效的地址,并且想要得到一个包含所有属性的哈希,所以我可以测试 e。 G。在我的控制器规范中创建客户。

post :create, {customer: !?!?!?}

为了完整起见,这是我的模型:

class Customer < ActiveRecord::Base
  has_one :address, foreign_key: :entity_id

  validates_presence_of :address
  accepts_nested_attributes_for :address
end

class Address < ActiveRecord::Base
  belongs_to :customer, foreign_key: :entity_id
end

【问题讨论】:

    标签: testing ruby-on-rails-4 associations factory-bot


    【解决方案1】:

    FactoryGirl 不支持此功能。在这里查看这个问题:https://github.com/thoughtbot/factory_girl/issues/359

    我认为这不是一个真正的大问题。就这样写吧:

    FactoryGirl.attributes_for(:customer, address: FactoryGirl.attributes_for(:address))
    

    【讨论】:

    • 最后是绿色的 :-) 我最终得到了 post :create, customer: attributes_for(:customer, address_attributes: attributes_for(:address))
    猜你喜欢
    • 2012-02-27
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多