ruby-on-rails
  • assertions
  • functional-testing
  • 2009-09-26 26 views 1 likes 
    1

    我的控制器能够创建一个子book_loan。我试图在功能测试中测试这种行为,但在使用assert_difference方法时遇到困难。我尝试了很多方法将book_loans的计数传递给assert_difference,但没有运气。断言在Ruby on Rails中关系中的子女数量的差异

    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) 
    

    回答

    3

    它看起来像assert_difference需要一个字符串,它将在块前后评估。所以下面可能适合你:

    assert_difference('books(:ruby_book).book_loans.count', 1) do 
        ... 
    end 
    
    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调用拉姆达来验证差异:

    assert_difference(lambda { account.users.count }, +1) do                          
        invite.accept(another_user) 
    end 
    
    相关问题