我正在测试发票模型(客户有很多发票,发票属于客户)并试图检查创建方法是否有效。
这就是我的想法:
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?
它只告诉我计数没有改变 - 所以我不确定问题是什么。我做错了什么?
答案 0 :(得分: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 }
在测试中。
另外,我必须更改valid_attributes中的数字。调试每一个验证都表明它与工厂中的相同 - 但必须是唯一的。这为我解决了!谢谢大家的帮助!