I have an Invoice
model that may contain a number of Items
as well:
我有一个发票模型可能也包含一些项目:
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
I am trying to test this using RSpec:
我正在尝试使用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
Unfortunately, this test (and all the others) fail with this error message from RSpec:
不幸的是,这个测试(以及所有其他测试)失败了,错误消息来自RSpec:
Failure/Error: @invoice = @user.invoices.create(FactoryGirl.attributes_for(:invoice))
ActiveModel::MassAssignmentSecurity::Error:
Can't mass-assign protected attributes: items
How can I create an invoice with items that will pass my tests?
我如何用通过测试的项目创建一个发票?
I am using FactoryGirl to fabricate objects like this:
我正在用factory - girl制作这样的物品:
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
2 个解决方案
#1
5
This is a stack answer I bookmarked when I was trying to figure it out:
这是我在试图找出答案的时候收藏的一个堆栈答案:
factory-girl-nested-factory
Edit: Sorry, just realized the answer was pure FactoryGirl and no rspec.
编辑:对不起,我刚意识到答案是纯工厂女孩,没有说明。
#2
1
Have you checked https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations?
你检查https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md协会吗?
There's a part about has_many-associations. Basically what it says is to extend your invoice-factory with one that adds some items after it created the invoice.
有一部分是关于has_many-associations的。基本上,它说的是扩展您的发票工厂,其中一个在创建发票后添加了一些项目。
#1
5
This is a stack answer I bookmarked when I was trying to figure it out:
这是我在试图找出答案的时候收藏的一个堆栈答案:
factory-girl-nested-factory
Edit: Sorry, just realized the answer was pure FactoryGirl and no rspec.
编辑:对不起,我刚意识到答案是纯工厂女孩,没有说明。
#2
1
Have you checked https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations?
你检查https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md协会吗?
There's a part about has_many-associations. Basically what it says is to extend your invoice-factory with one that adds some items after it created the invoice.
有一部分是关于has_many-associations的。基本上,它说的是扩展您的发票工厂,其中一个在创建发票后添加了一些项目。