1

一个Bookhas_manyReviews和一个Reviewbelongs_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

我已经放弃了数据库并从一个空白开始。我有两个问题:

  1. 我只创建了一个与一本书相关的评论。为什么Review.count打印 3 和 2 而不是 1 和 0?

  2. 为什么断言期望 4,但收到 2?

谢谢。

4

2 回答 2

5

这条线告诉您期望加一(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

于 2014-05-08T12:17:42.500 回答
4

您有 3 条记录。如果你写assert_difference 'Review.count', 1... 它期望最后是 4。但是如果你写assert_difference 'Review.count', -1……它期望 2,因此少 1。

于 2013-09-18T10:09:48.410 回答