【问题标题】:Can't use session variables in integration test in rails无法在 Rails 的集成测试中使用会话变量
【发布时间】:2016-04-12 04:10:24
【问题描述】:

我在集成测试中使用存储的会话 return_to URL 时遇到问题。

因为我的控制器可以从不同的地方访问,所以我将引用者存储在 new 操作的会话中,并在我的 create 操作中重定向到它。

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

由于我只在测试中使用 create 操作,因此我想像在单元测试中一样在集成测试中设置会话变量,但它不起作用。我总是被重定向到根路径。

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 或类似工具之类的东西。

我也尝试提供会话变量作为请求的一部分,就像 rails 指南描述的功能测试一样,没有效果:

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案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)。其余的测试保持不变。

    【讨论】:

    • 工作,谢谢。没想到我必须明确设置引用者。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 2011-08-20
    • 2013-03-22
    相关资源
    最近更新 更多