使用会话 sinatra 进行 Rspec 测试

发布于 2024-08-25 16:16:04 字数 81 浏览 2 评论 0原文

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

我使用 Rspec + sinatra

Tks

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

I using Rspec + sinatra

Tks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

記憶穿過時間隧道 2024-09-01 16:16:04

此页面,展示了测试会话的主要问题与rspecsinatra

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

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

它将允许从测试代码的最后一个请求访问模拟会话对象。

这是我的控制器代码,它读取 code 参数并将其值存储在 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

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

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.

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

Then here's test code:

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
放手` 2024-09-01 16:16:04

与所有其他页面相同。

你需要澄清你的问题。测试会话有什么问题。如果问题是用户需要登录,那么您可以在规范文件中使用类似的内容:

before :each do
  post "/login", {:username => "myuser", :password => "mypass"}
end

它将在每次测试之前让您登录。

Same like all other pages.

You need to clarify your question. What is problem with testing session. If problems is that user need to be logged in, then you can use something like this in spec file:

before :each do
  post "/login", {:username => "myuser", :password => "mypass"}
end

which will log you in before each test.

め可乐爱微笑 2024-09-01 16:16:04

我只能通过禁用测试环境的会话来使其工作。这篇博文有一个很好的例子: http://benprew.posterous.com/testing-sessions -with-sinatra

I was only able to get it to work by disabling sessions for the test environment. This blog post has a good example: http://benprew.posterous.com/testing-sessions-with-sinatra

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文