使用 accepts_nested_attributes_for 为 FactoryGirl 对象生成嵌套属性

Generating nested attributes for FactoryGirl objects with accepts_nested_attributes_for

我正在使用 RSpec 和 Factory Girl 来测试我的应用程序。我想做的是:我有一个接受嵌套属性的对象,但该嵌套属性无效。我想测试 POST 是否有效:

let(:valid_attributes) { build(:user).attributes }
it "creates a new User" do      
  expect {
    post :create, {user: valid_attributes}, valid_session
  }.to change(User, :count).by(1)
end

那是工厂:

FactoryGirl.define do
  factory :user do |x|
    name "Homer"
    after(:build) do
      build :address
    end
  end
end

问题是 build(:user).attributes 返回的散列没有 address,尽管如果我检查 build(:user) 创建的对象,address 是正确的建成。

有什么方法可以轻松生成具有嵌套属性的散列吗?

你可以自定义你的对象,同时通过参数构建它,所以我会这样解决你的任务:

let(:valid_attributes) { attributes_for(:user, address: attributes_for(:address)) }

回答自己以展示技术上可行的解决方案:

let(:valid_attributes) {attributes_for(:user, address_attributes: attributes_for(:address))}

这行得通,但我觉得它很笨重。在复杂的情况下,代码会变得非常冗长和丑陋。正如我所期望的那样,我不会将此作为解决方案投票。