我的控制器可以创建子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 )
答案 0 :(得分:3)
看起来assert_difference需要一个字符串,它将在块之前和之后进行评估。以下内容可能对您有用:
assert_difference('books(:ruby_book).book_loans.count', 1) do
...
end
答案 1 :(得分: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
无法在运行块之前和运行块之后执行操作 。
字符串有效的原因是字符串可以评估以确定是否产生了预期的差异。
但字符串是一个字符串,不是代码。我认为更好的方法是传递可以调用的东西。将表达式包装在lambda
就可以了;它允许assert_difference
调用lambda来验证差异:
assert_difference(lambda { account.users.count }, +1) do
invite.accept(another_user)
end