2016-04-11 6 views
2

レールに統合テストでセッション変数を使用することはできません。は、私は私の統合テストで私のセッション保存<code>return_to</code> URLを使用して問題を持っている

私のコントローラは、可能性があるので、私は新しい行動上のセッションでリファラを保存し、私のアクションを作成して、それにリダイレクト別の場所からアクセスします。

cards_controller.rb: 
class CardsController < ApplicationController 
... 
    def new 
    @card = current_user.cards.build 
    session[:return_to] ||= request.referer 
    end 

    def create 
    @card = current_user.cards.build(card_params) 
    if @card.save 
     flash[:success] = 'Card created!' 
     redirect_to session.delete(:return_to) || root_path 
    else 
     render 'new', layout: 'card_new' 
    end 
    end 
... 
end 

私は私のテストで作成アクションを使用すると、私は私が私のユニットテストでそうであるように、統合テストでセッション変数を設定したいと思いますが、それは動作しません。私はいつもルートパスにリダイレクトされます。

cards_interface_test.rb: 
class CardsInterfaceTest < ActionDispatch::IntegrationTest 
    test 'cards interface should redirect after successful save' do 
    log_in_as(@user) 
    get cards_path 
    assert_select 'a[aria-label=?]', 'new' 
    name = "heroblade" 
    session[:return_to] = cards_url 
    assert_difference 'Card.count', 1 do 
     post cards_path, card: { name: name, icon: 'white-book', color: 'indigo', contents: 'subtitle | Rogue feature'} 
    end 
    assert_redirected_to cards_url 
    follow_redirect! 
    assert_match name, response.body 
    assert_select 'td', text: name 
    end 
end 

assert_redirected_to行でテストが失敗します。

は、私が最初に get new_card_pathを呼び出そうとしましたが、何の違いをしなかったし、今私は少し迷ってしまいました。これが基本的にうまくいくかどうかわかりませんが、小さな間違いをしたり、ベストプラクティスに対して完全に何かをしようとすると、セレンなどのツールを使用するすべてのインターフェーステストをリファクタリングする必要があります。

私はレールガイドのような要求の一部としてセッション変数を提供するだけでなくしようとしたが、効果なしと機能テストのために説明します。手動で設定セッションは統合で可能な場合

post cards_path, {card: { name: name, icon: 'white-book', color: 'indigo', contents: 'subtitle | Rogue feature' }}, {'return_to' => cards_url} 

答えて

1

私は知りませんテスト(ではない、むしろ推測)が、それだけで通常のHTTPヘッダですので、あなたがリファラを設定することができるはずです。ヘッダは統合テストのリクエストメソッドヘルパー(get等)に3rd parameterとして渡すことができます。

したがって、最初にアクションをrefererヘッダーセットで呼び出して(セッションに入るように)、リダイレクトを含めてcreateアクションが機能するはずです。

class CardsInterfaceTest < ActionDispatch::IntegrationTest 
    test 'cards interface should redirect after successful save' do 
    log_in_as(@user) 

    # visit the 'new' action as if we came from the index page 
    get new_card_path, nil, referer: cards_url 

    assert_difference 'Card.count', 1 do 
     post cards_path, card: { name: name, icon: 'white-book', color: 'indigo', contents: 'subtitle | Rogue feature'} 
    end 
    assert_redirected_to cards_url 
    # ... 
    end 
end 

まず、我々はインデックスページから来たかのように(リファラがsessionに入ることができるように)リファラセットでnewアクションを取得してみてください。残りのテストは同じままです。

+0

は、THX働きました。私はリファラーを明示的に設定しなければならないと考えなかった。 –

関連する問題