【问题标题】:Generating nested attributes for FactoryGirl objects with accepts_nested_attributes_for使用 Accepts_nested_attributes_for 为 FactoryGirl 对象生成嵌套属性
【发布时间】:2015-09-21 16:10:46
【问题描述】:

我正在使用 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 是正确构建的。

有没有什么方法可以轻松生成带有嵌套属性的哈希?

【问题讨论】:

    标签: ruby-on-rails ruby rspec factory-bot nested-attributes


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这似乎不起作用,地址是空白的。另外,当你提交它时,我猜 address_attributes 是预期的,而不是地址作为键。另外,如果你有多个嵌套属性,看起来工作量很大:/
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      • 2018-07-31
      相关资源
      最近更新 更多