Book
has_many Reviews
和Review
belongs_to Book
。我使用的是rails 4.0和ruby 2.0.0p247
我按如下方式运行测试:
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 => "KP@KP.com",
: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
正如您所看到的,我在删除与书籍相关的评论之前和之后打印了计数,并且它减少了1.但是,断言期望并收到不正确的计数,将其显示为错误:
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
我放弃了数据库并开始使用空白数据库。我有两个问题:
我只创建了一本与一本书相关的评论。为什么Review.count
打印3和2与1和0相对应?
为什么断言期望4,但收到2?
感谢。
答案 0 :(得分:5)
此行表示您期望Plus 1(1或+1)的差异。
assert_difference 'Review.count', 1 , "a review should be deleted"
但实际上你想要负一(-1)的差异,所以你应该写
assert_difference 'Review.count', -1 , "a review should be deleted"
如需更多指南,请访问assert_difference
答案 1 :(得分:4)
你有3条记录。
如果你写assert_difference 'Review.count', 1
...它最后会有4个。
但是如果你写assert_difference 'Review.count', -1
...它预期2,因此减少1。