我正在测试一个发票模型(一个客户有很多发票,一个发票属于一个客户)并试图检查 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?
它只是告诉我计数没有改变一 - 所以我不确定问题是什么。我究竟做错了什么?