2013-01-02 10 views
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丟失了?

這只是告訴我,伯爵並沒有改變 - 所以我不知道問題是什麼。我究竟做錯了什麼?

+0

'create'方法是如何工作的?我假設它希望它的參數是屬性的散列,而不是已經初始化的「發票」對象? – gregates

+0

請參閱問題編輯。我添加了create方法。是的,它想要一個:invoice params hash。 – weltschmerz

+0

看起來您最有可能在您的發票上收到驗證錯誤,該錯誤不會將任何內容保存到數據庫,也不會增加發票計數。我建議使用'create!'和/或'save!'做一個單元級別的測試,如果因爲任何原因無法保存發票,這會引發實際的異常。 –

回答

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中的數字。調試每一次驗證都表明它和工廠一樣 - 但必須是唯一的。這爲我解決了它!感謝大家的幫助!

相關問題