一个Book
has_manyReviews
和一个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?
谢谢。