断言 Ruby on Rails 中关系中孩子数量的差异
我的控制器能够创建子 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 )
My controller is able to create a child book_loan. I am trying to test this behavior in a functional test but am having a hard time using the assert_difference method. I've tried a number of ways of passing the count of book_loans to assert_difference with no luck.
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
can't convert BookLoan into String
assert_difference(books(:ruby_book).book_loans,:count, 1)
NoMethodError: undefined method 'book_loans' for #
assert_difference('Book.book_loans.count', +1)
can't convert Proc into String
assert_difference( lambda{books(:ruby_book).book_loans.count}, :call, 1 )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来assert_difference需要一个字符串,它将在块之前和之后评估该字符串。因此,以下内容可能适合您:
It looks like assert_difference expects a string, which it will eval before and after the block. So the following may work for you:
我也遇到了这个问题,只是想知道这是如何工作的。就像原来的帖子一样,我也尝试过这样的事情:
这不起作用,因为
assert_difference
无法在运行块之前和之后执行操作它运行该块。该字符串起作用的原因是可以评估该字符串以确定是否产生了预期的差异。
但字符串就是字符串,不是代码。我相信更好的方法是传递一些可以调用的东西。将表达式包装在 lambda 中即可实现此目的;它允许
assert_difference
调用 lambda 来验证差异:I was having trouble with this too and just figured out how this works. Like the original post, I too was trying something like this:
This doesn't work because there is no way for
assert_difference
to perform an action before it runs the block and after it runs the block.The reason the string works is that the string can be evaluated to determine if the expected difference resulted.
But a string is a string, not code. I believe a better approach is to pass something that can be called. Wrapping the expression in a
lambda
does just that; it allowsassert_difference
to call the lambda to verify the difference: