gpt4 book ai didi

ruby-on-rails - 如何使用 RSpec 测试具有嵌套属性的表单?

转载 作者:行者123 更新时间:2023-12-04 06:03:09 27 4
gpt4 key购买 nike

我有一个 Invoice 模型,它可能包含许多 Items:

class Invoice < ActiveRecord::Base

attr_accessible :number, :date, :recipient, :items_attributes

belongs_to :user

has_many :items

accepts_nested_attributes_for :items, :reject_if => :all_blank, :allow_destroy => true

end

我正在尝试使用 RSpec 对此进行测试:

describe InvoicesController do

describe 'user access' do

before :each do
@user = FactoryGirl.create(:user)
@invoice = @user.invoices.create(FactoryGirl.attributes_for(:invoice))
sign_in(@user)
end

it "renders the :show view" do
get :show
expect(response).to render_template :show
end

end

end

不幸的是,此测试(以及所有其他测试)失败并显示来自 RSpec 的错误消息:

Failure/Error: @invoice = @user.invoices.create(FactoryGirl.attributes_for(:invoice))
ActiveModel::MassAssignmentSecurity::Error:
Can't mass-assign protected attributes: items

如何创建包含将通过测试的项目的发票?

我正在使用 FactoryGirl 来制作这样的对象:

factory :invoice do
number { Random.new.rand(0..1000000) }
recipient { Faker::Name.name }
date { Time.now.to_date }
association :user
items { |i| [i.association(:item)] }
end

factory :item do
date { Time.now.to_date }
description { Faker::Lorem.sentences(1) }
price 50
quantity 2
end

最佳答案

-要在您的示例中使用嵌套属性,您需要传入“item_attributes”而不是像您当前正在执行的“items”。

我对 FactoryGirl 不是很流利,但也许按照这些思路行事? :

invoice_attributes = FactoryGirl.attributes_for(:invoice)
invoice_attributes["item_attributes"] = invoice_attributes["items"]
invoice_attributes["items"] = nil
@invoice = @user.invoices.create(invoice_attributes)

s 应该模拟从您的表单传入的参数。

关于ruby-on-rails - 如何使用 RSpec 测试具有嵌套属性的表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15231564/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com