我有一个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