2016-04-11 85 views
2

我在我的集​​成测试中使用我的会话存储return_to 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第一次,但没有什么区别,现在我有点失落。我不知道这是否应该基本上工作,但我犯了一个小错误,或者如果我试图完全对付最佳做法,并应重构所有我的界面测试使用像Selenium或类似的工具。

我试着以及提供会话变量像铁轨引导请求的一部分描述为没有效果功能测试:

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

回答

1

我不知道,如果手动设置会话是可能的整合测试(猜测不是),但你应该能够设置引用者,因为它只是一个普通的HTTP头。在集成测试中,可以将标题作为3rd parameter传递给请求方法助手(get等)。

所以,我认为你应该首先调用new动作与引用头设置(以便它进入会话),然后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 

首先,我们尝试让new行动引荐集因为如果我们从索引页(这样引用者可以进入session)来了。其余的测试保持不变。

+0

工作,thx。没有想到我必须明确地设置引用者。 –