2
我正在測試一個發票模型(客戶有很多發票,發票屬於一個客戶),並試圖檢查create方法是否工作。Rspec嵌套控制器創建方法不會增加計數1
這是我想出了:
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:
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丟失了?
這只是告訴我,伯爵並沒有改變 - 所以我不知道問題是什麼。我究竟做錯了什麼?
'create'方法是如何工作的?我假設它希望它的參數是屬性的散列,而不是已經初始化的「發票」對象? – gregates
請參閱問題編輯。我添加了create方法。是的,它想要一個:invoice params hash。 – weltschmerz
看起來您最有可能在您的發票上收到驗證錯誤,該錯誤不會將任何內容保存到數據庫,也不會增加發票計數。我建議使用'create!'和/或'save!'做一個單元級別的測試,如果因爲任何原因無法保存發票,這會引發實際的異常。 –