使用Webrat测试时如何处理Cookie? [英] How to handle cookies when testing with Webrat?
问题描述
我正在使用Webrat为基于Sinatra的应用程序编写Cucumber测试.对于某些测试,我需要实现
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"
我定义这样的步骤:
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
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
看起来Webrat没有存储cookie.测试不会报告任何错误,但是会显示"logged_in?".在视图中始终为假,例如未保存cookie.
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.
我做错什么了吗?如果这只是Webrat的工作方式,那么最佳的解决方法是什么?
Am I doing something wrong? If this is just how Webrat works, what is the best workaround?
推荐答案
真正的问题是Sinatra在测试环境中处理会话的方式.搜索Google网上论坛以进行讨论,但真正的解决方案是简单地使用:
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:
use Rack::Session::Cookie
和不
enable :sessions
使用硒很不错,但是作为解决OP问题的解决方案是过大的.
Using Selenium is nice but it's overkill as a solution for the OP's problem.
这篇关于使用Webrat测试时如何处理Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!