ruby-on-rails
  • assertions
  • functional-testing
  • 2009-09-26 59 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 
    
    相關問題