2

我正在测试一个发票模型(一个客户有很多发票,一个发票属于一个客户)并试图检查 create 方法是否有效。

这就是我想出的:

before do
  @valid_invoice = FactoryGirl.create(:invoice)
  @valid_client = @valid_invoice.client
end

it "creates a new Invoice" do
    expect {
      post :create, { invoice: @valid_client.invoices.build(valid_attributes), client_id: @valid_client.to_param }
    }.to change(Invoice, :count).by(1)
  end

这是我的发票工厂:

FactoryGirl.define do
    factory :invoice do
        association :client
        gross_amount 3.14
        net_amount 3.14
        number "MyString"
        payment_on "2013-01-01"
        vat_rate 0.19
    end
end

这是 invoices_controller 中的 create 方法:

def create
@client = Client.find(params[:client_id])
@invoice = @client.invoices.build(params[:invoice])

respond_to do |format|
  if @invoice.save
    format.html { redirect_to([@invoice.client, @invoice], :notice => 'Invoice was successfully created.') }
    format.json { render :json => @invoice, :status => :created, :location => [@invoice.client, @invoice] }
  else
    format.html { render :action => "new" }
    format.json { render :json => @invoice.errors, :status => :unprocessable_entity }
  end
end
end

这些是有效属性,即成功创建发票所需的属性:

def valid_attributes
{
  gross_amount: 3.14,
  net_amount: 3.14,
  number: "MyString",
  payment_on: "2013-01-01",
  vat_rate: 0.19
}
end

这些都是有效的。也许缺少client_id?

它只是告诉我计数没有改变一 - 所以我不确定问题是什么。我究竟做错了什么?

4

1 回答 1

1

@gregates - 你的回答是对的,你为什么要删除它?:-) 再次发布,我会检查它作为最佳答案。

这是解决方案:

post :create, { invoice: valid_attributes, client_id: @valid_client.to_param }, valid_session

代替

post :create, { invoice: @valid_client.invoices.build(valid_attributes), client_id: @valid_client.to_param }

在测试中。

Also, I had to change the number in the valid_attributes. Debugging every single validation showed me that it was the same as in the factory - but must instead be unique. This solved it for me! Thanks for everyone's help!

于 2013-01-02T22:38:44.457 回答