在我的Rails项目中,我有一个User
可以有很多Projects
,而Invoices
可以有很多Invoice
。每个Items
都可以有多个嵌套class Invoice < ActiveRecord::Base
attr_accessible :number, :date, :recipient, :project_id, :items_attributes
belongs_to :project
belongs_to :user
has_many :items, :dependent => :destroy
accepts_nested_attributes_for :items, :reject_if => :all_blank, :allow_destroy => true
validates :project_id, :presence => true
def build_item(user)
items.build(:price => default_item_price(user), :tax_rate => user.preference.tax_rate)
end
def set_number(user)
self.number ||= (user.invoices.maximum(:number) || 0).succ
end
end
class InvoicesController < ApplicationController
def new
@invoice = current_user.invoices.build(:project_id => params[:project_id])
@invoice.build_item(current_user)
@invoice.set_number(current_user)
@title = "New invoice"
end
def create
@invoice = current_user.invoices.build(params[:invoice])
if @invoice.save
flash[:success] = "Invoice created"
redirect_to invoices_path
else
render :new
end
end
end
。
it "saves the new invoice in the database" do
expect {
post :create, invoice: attributes_for(:invoice, project_id: @project, items_attributes: [ attributes_for(:item) ])
}.to change(Invoice, :count).by(1)
end
现在,我正在尝试使用RSpec和FactoryGirl测试发票的创建,除了与 POST create 操作相关的测试外,所有测试都通过,例如:
Failure/Error: expect {
count should have been changed by 1, but was changed by 0
它一直给我这个错误:
factories.rb
有人能告诉我为什么会这样吗?
这是我用来制作物品的FactoryGirl.define do
factory :invoice do
number { Random.new.rand(0..1000000) }
recipient { Faker::Name.name }
date { Time.now.to_date }
association :user
association :project
end
factory :item do
date { Time.now.to_date }
description { Faker::Lorem.sentences(1) }
price 50
quantity 2
tax_rate 10
end
end
:
{{1}}
有人可以帮忙吗?
...谢谢