1

我的控制器能够创建一个子 book_loan。我试图在功能测试中测试这种行为,但很难使用 assert_difference 方法。我尝试了多种将 book_loans 计数传递给 assert_difference 的方法,但都没有成功。

  test "should create loan" do
    @request.env['HTTP_REFERER'] = 'http://test.com/sessions/new'
    assert_difference(books(:ruby_book).book_loans.count, 1) do
      post :loan, {:id => books(:ruby_book).to_param,
                               :book_loan => {:person_id => 1,
                                              :book_id =>
                                                books(:dreaming_book).id}}

    end
  end

无法将 BookLoan 转换为字符串

assert_difference(books(:ruby_book).book_loans,:count, 1)

NoMethodError:未定义的方法“book_loans”用于#

assert_difference('Book.book_loans.count', +1)

无法将 Proc 转换为字符串

assert_difference( lambda{books(:ruby_book).book_loans.count}, :call, 1 )
4

2 回答 2

3

看起来 assert_difference 需要一个字符串,它将在块之前和之后对其进行评估。因此,以下内容可能对您有用:

assert_difference('books(:ruby_book).book_loans.count', 1) do
  ...
end
于 2009-09-26T00:28:13.937 回答
2

我也遇到了麻烦,只是弄清楚了它是如何工作的。就像原来的帖子一样,我也在尝试这样的事情:

# NOTE: this is WRONG, see below for the right way.
assert_difference(account.users.count, +1) do                                                                                                       
  invite.accept(another_user)
end

这不起作用,因为在运行块之前和运行块之后都assert_difference无法执行操作。

字符串起作用的原因是可以评估字符串以确定是否产生了预期的差异。

但是字符串是字符串,而不是代码。我相信更好的方法是传递可以调用的东西。将表达式包装在 alambda中就是这样做的;它允许assert_difference调用 lambda 来验证差异:

assert_difference(lambda { account.users.count }, +1) do                                                                                                       
  invite.accept(another_user)
end
于 2012-09-27T19:32:20.757 回答