Reputation: 13879
A Book
has_many Reviews
and a Review
belongs_to Book
. I am using rails 4.0 and ruby 2.0.0p247
I am running the test as follows:
test "DELETE destroy should decrement review count by 1" do
book = Book.create({
:isbn=>"1234567890",
:title=>"Dummies Guide to Rails",
:author=>"KP",
:description=>"lorem ipsum"
})
# assert_not_nil Book.find_by_isbn('1234567890')
review = Review.create!({
:book_id => book.id,
:name => "KP",
:email => "[email protected]",
:description => "Good book.",
# :book => book
})
assert_difference 'Review.count', 1 , "a review should be deleted" do
puts Review.count # => 3
delete :destroy, :book_id => book.id, :id => review.id
assert_response :redirect
puts Review.count # => 2
end
# puts Review.count
assert_nil Review.find_by_id(review.id)
end
As you can see, I have printed the count, before and after deleting the review associated with a book, and it decreases by 1. However, the assertions expects and receives incorrect counts, showing this as the error:
1) Failure:
ReviewsControllerTest#test_DELETE_destroy_should_decrement_review_count_by_1 [test/controllers/reviews_controller_test.rb:56]:
a review should be deleted.
"Review.count" didn't change by 1.
Expected: 4
Actual: 2
I have dropped the db and started with a blank one. I have two questions:
I have only created one review associated with one book. Why is the Review.count
printing 3 and 2 as against 1 and 0?
Why does the assertion expect 4, but receive 2?
Thanks.
Upvotes: 2
Views: 4141
Reputation: 6959
This line tells that you are expecting the difference of Plus one(1 or +1).
assert_difference 'Review.count', 1 , "a review should be deleted"
But actually you want the difference in Negative one(-1), so you should write
assert_difference 'Review.count', -1 , "a review should be deleted"
For more guide visit assert_difference
Upvotes: 6
Reputation: 5798
You have 3 records.
If you write assert_difference 'Review.count', 1
... it expects 4 at the end.
But if you write assert_difference 'Review.count', -1
... it expects 2, thus 1 less.
Upvotes: 5