I am testing an Invoice model (a Client has many invoices, an Invoice belongs to a Client) and trying to check whether the create method works.
This is what I have come up with:
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
This is my invoice factory:
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
This is the create method in the 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
And these are the valid attributes, ie the attributes needed for an invoice to be created successfully:
def valid_attributes
{
gross_amount: 3.14,
net_amount: 3.14,
number: "MyString",
payment_on: "2013-01-01",
vat_rate: 0.19
}
end
These are all valid. Maybe the client_id is missing?
It is only telling me that the count did not change by one – so I am not sure what the problem is. What am I doing wrong?
@gregates – Your answer was right, why did you remove it? 🙂 Post it again and I will check it as best answer.
This is the solution:
instead of
in the test.
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!