2

在我的 Rails 项目中,我有一个Userthat can have many 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

现在,我正在尝试使用 RSpec 和 FactoryGirl 测试发票的创建,并且所有测试都通过了,除了与POST 创建操作相关的测试,例如:

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

它一直给我这个错误:

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

有人可以帮忙吗?

谢谢...

4

0 回答 0