2014-12-25 82 views
0

我有以下試驗: 測試/集成/ authentication_test.rb:滑軌單元測試assert_template失敗

require 'test_helper' 

class AuthenticationTest < ActionDispatch::IntegrationTest 

    def setup 
    @admin = users(:barry) # grab user from fixtures 
    end 

    test "trying to view a user before logging in" do 
    get user_path(@admin) 
    assert_template 'sessions/new' 
    assert_not flash.empty? 
    assert_select "div#error_explanation" 
    assert_select "div.field_with_errors" 
    assert_select "a[href=?]", logout_path, count: 0 
    assert_not is_logged_in? 
    end 
end 

的測試失敗,錯誤如下:

FAIL["test_trying_to_view_a_user_before_logging_in", AuthenticationTest, 2.206536] test_trying_to_view_a_user_before_logging_in#AuthenticationTest (2.21s) 
    expecting <"sessions/new"> but rendering with <[]> 
    test/integration/authentication_test.rb:11:in `block in <class:AuthenticationTest>' 

的users_controller的相關位.rb:

class UsersController < ApplicationController 

    before_action :logged_in_user, only: [:index, :show, :edit, :update, :destroy] 

    def show 
    @user = User.find_by_callsign(params[:callsign]) 
    @page_name = "user_page" 
    redirect_to root_url and return unless @user.activated 
    end 
    . 
    . 
end 

sessions_helper.rb:

def logged_in_user 
    unless logged_in? 
    store_location 
    flash[:danger] = "Please log in." 
    redirect_to login_url 
    end 
end 

def logged_in? 
    !current_user.nil? 
end 

在routes.rb中:

get 'login', to: 'sessions#new' 

我不明白爲什麼測試失敗。當我手動執行這些步驟時,它一切正常。 assert_template是否存在已知問題?當我在測試中註釋掉assert_template 'sessions/new'時,它會通過。

編輯:

在日誌/ test.log中:的確是重定向到正確的模板(重定向到http://www.example.com/dominos/newname)。但它沒有任何「渲染」線。失敗的測試的最後幾行是:

Redirected to http://www.example.com/dominos/newname 
Completed 302 Found in 21ms (ActiveRecord: 2.5ms) 
    [1m[35m (0.4ms)[0m SELECT COUNT(*) FROM "personas" 
    [1m[36m (0.2ms)[0m [1mROLLBACK[0m 

在涉及assert_template成功測試test.log中的文件,也有不同的「渲染」下一個重定向行,例如:

Rendered personas/new.html.erb within layouts/application (2.0ms) 

這可能是測試失敗的原因嗎?爲什麼頁面不呈現?

+0

運行此測試時,請查看'log/test.log'文件中的內容,並與手動執行步驟中的'log/development.log'文件內容進行比較。很可能測試正在採取不同的路線,並出現錯誤或其他問題。 –

+0

謝謝。測試日誌顯示它確實重定向到正確的模板('重定向到http:// www.example.com/dominos/newname')。但它沒有任何「渲染」線條,這可能是問題的一部分嗎? (見編輯) – Bazley

回答

2

另一個解決將是使用assert_redirected_to

4

在這樣的集成測試中,get語句不遵循重定向。要遵循重定向,請使用get_via_redirect。更多信息是here

+0

謝謝大家,現在就開始工作吧! – Bazley

0

顯然我遲到了,但SaulGoodman。我遇到了一個非常類似的問題,所以你的帖子很有用。我發現如果涉及重定向,assert_template方法不起作用。只有在頁面被「渲染」的情況下才是可靠的。我認爲。也許我錯了,但這是我慢慢接受的教訓。希望你解決這個問題。

1

我用follow_redirect!強制測試重定向。然後我可以通過assert_template檢查它是否重定向到正確的頁面。