使用会话 sinatra 使用 Rspec 进行测试

问题描述:

我有使用 session 的 sinatra 应用程序,如何测试使用 session 的页面?

I have sinatra appliction using session, how do I test a page that uses session?

我使用 Rspec + sinatra

I using Rspec + sinatra

谢谢

这个页面,展示了使用rspecsinatra 测试会话的主要问题.

This page, show's the main problem of testing session with rspec and sinatra.

主要问题是变量 session 无法从测试代码访问.为了解决它,它建议(并且我确认)在 spec/spec_helper.rb 中添加 fowling 行:

The main problem is that the variable session is not accessible from the test code. To solve it, it suggests (and I confirm) to add the fowling lines at spec/spec_helper.rb:

def session
  last_request.env['rack.session']
end

它将使来自测试代码的最后一个请求的模拟会话对象可访问.

It will make accessible a mocked session object from the last request at the test code.

这是我的控制器代码,它读取 code 参数并将其值存储在 session 中:

Here's my controller code that read's a code param and stores its value at session:

post '/step2callback' do
  session['code'] = params['code']
end

然后是测试代码:

context "making an authentication" do
  before do
    post "/step2callback", code: "code_sample"
  end
  it "reads the param code and saves it at session" do
    expect(session['code']).to eq("code_sample")
  end  
end