【问题标题】:Access the session in my API spec访问我的 API 规范中的会话
【发布时间】:2012-06-14 07:05:44
【问题描述】:

我正在开发一个 API 并想测试登录方法。 API 的规范位于 spec/api/ 而不是 spec/controller。我正在使用 rspec-rails。现在我有一个这样的规范:

describe "/api/login.json", :type => :api do
  let(:user) { FactoryGirl.create(:user) }

  context "when called with correct credentials" do
    before(:all) do
      post "/api/v1/passenger/login.json",:email => user.email, :password => user.password
    end

    it "responds with HTTP 200" do
      last_response.status.should == 200
    end

    it "sets the session correctly" do
      session[:user_id].should == user.id # <-- ### Here ###
    end
  end
end

失败了。 session 为零。如何访问会话变量?

我想我必须在 RSpec.configure 块中包含一些内容?

【问题讨论】:

  • 你可以试试request.session,但我不确定它是否有效。
  • request 是由Rack::Test::Methods 定义的方法,我将它包含在我的帮助程序中以进行:type =&gt; :api 测试。它是一种类似于postget 的方法,需要一个URL 作为参数。所以request.session 只是抛出ArgumentError Exception: wrong number of arguments (0 for 1)
  • Api::LoginController 是否在描述链上被描述得更高?我想知道是否混入了 ActionController::TestCase::Behavior。你可以访问 controller.session 吗?

标签: ruby-on-rails rspec


【解决方案1】:

如果您的会话已启用,我想您可以通过env['rack.session'] 获得它。

我也会向你推荐这个 tut http://railscasts.com/episodes/280-pry-with-rails 使用 pry 有很多好处,你可以在你的 spec 中写上binding.pry 并调试它

【讨论】:

    【解决方案2】:

    大约之后。 200 小时的谷歌搜索,我自己找到了答案。

    归结为这些神奇的词:

    module FoobarHelper
      def session
        last_request.env['rack.session']
      end
    end
    
    RSpec.configure do |c|
      c.include FoobarHelper, :type => :api
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-15
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 2014-08-25
      相关资源
      最近更新 更多