使用Webrat测试时如何处理cookie?
我正在使用 Webrat 为基于 Sinatra 的应用程序编写 Cucumber 测试。 对于某些测试,我需要实现一个像
Given I am logged in as admin
When I am visiting "/"
Then I should see "Settings"
我定义的步骤这样的场景:
Given /^I am logged in as "(.+)"$/ do |user|
visit "/login"
fill_in "login", :with => user
fill_in "password", :with => "123456"
click_button "Login"
end
When /^I am viewing "(.+)"$/ do |url|
visit(url)
end
Then /^I should see "(.+)"$/ do |text|
response_body.should =~ /#{text}/
end
成功时,将创建一个 cookie
response.set_cookie(cookie_name, coockie_value)
,然后当用户尝试通过帮助程序方法访问管理页面时在视图中进行验证:
def logged_in?
request.cookies[cookie_name] == cookie_value
end
并且看起来 Webrat 不存储 cookie。 测试不会报告任何错误,但会报告“logged_in?” 在视图中总是错误的,就像 cookie 没有保存一样。
难道我做错了什么? 如果这就是 Webrat 的工作方式,那么最好的解决方法是什么?
I'm writing Cucumber tests for a Sinatra based application using Webrat. For some tests I need to implement a scenario like
Given I am logged in as admin
When I am visiting "/"
Then I should see "Settings"
I define steps like this:
Given /^I am logged in as "(.+)"$/ do |user|
visit "/login"
fill_in "login", :with => user
fill_in "password", :with => "123456"
click_button "Login"
end
When /^I am viewing "(.+)"$/ do |url|
visit(url)
end
Then /^I should see "(.+)"$/ do |text|
response_body.should =~ /#{text}/
end
On success a cookie is created
response.set_cookie(cookie_name, coockie_value)
and then verified in views when user tries to access admin pages via helper method:
def logged_in?
request.cookies[cookie_name] == cookie_value
end
And it looks like Webrat doesn't store cookies. Tests don't report any error, but "logged_in?" in views is always false, like the cookie was not saved.
Am I doing something wrong? If this is just how Webrat works, what is the best workaround?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
真正的问题是 Sinatra 在测试环境中处理会话的方式。 在 Google 小组中搜索讨论,但真正的解决方案是简单地使用:
并且 不
使用 Selenium 很好,但作为 OP 问题的解决方案,它有点过分了。
The real problem is the way Sinatra is treating sessions in the test environment. Search the Google group for the discussion, but the real solution is to simply use:
and not
Using Selenium is nice but it's overkill as a solution for the OP's problem.
解决方法是使用带有 Selenium 后端的 Webrat。 它在单独的 Firefox 窗口中运行所有测试,因此 cookie 或 javascript 不是问题。 缺点是需要额外的时间和资源来运行 Firefox 并执行所有实际的点击、渲染等操作。
The workaround is use Webrat with Selenium back end. It runs all tests in a separate Firefox window, so cookies or javascript is not a problem. The downside is extra time and resources required to run Firefox and do all the real clicks, rendering etc.
您可以对“给定/^我已登录”步骤 hack
logged_in?
:有两个缺点:
You could have your "Given /^I am logged in" step hack
logged_in?
:There are two downsides: