我有一个Invoice
模型可能包含许多Items
还有:如何在Ruby on Rails中使用FactoryGirl嵌套属性创建测试对象?
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
好的,谢谢,但我无法让它以这种方式工作。 – Tintin81 2013-03-05 17:11:16