黄瓜测试重定向

ast*_*nic 11 testing ruby-on-rails cucumber

找到了一些建议:http://openmonkey.com/articles/2009/03/cucumber-steps-for-testing-page-urls-and-redirects

我已经将上述方法添加到我的Web步骤定义中,编写了我的功能,运行它并得到有关nil对象的错误.经过一番调查,我注意到,我没有回应并请求对象,它们是零

来自web_steps.rb:

Then /^I should be on the (.+?) page$/ do |page_name|
  request.request_uri.should == send("#{page_name.downcase.gsub(' ','_')}_path")
  response.should be_success
end

Then /^I should be redirected to the (.+?) page$/ do |page_name|
  request.headers['HTTP_REFERER'].should_not be_nil
  request.headers['HTTP_REFERER'].should_not == request.request_uri
  Then "I should be on the #{page_name} page"
end
Run Code Online (Sandbox Code Playgroud)

请求和响应对象是零,为什么?

小智 23

您是否正在使用WebRat或Capybara作为Cucumber中的驱动程序?你可以看看features/support/env.rb.我正在使用Capybara,所以我的包括以下几行:

  require 'capybara/rails'
  require 'capybara/cucumber'
  require 'capybara/session'
Run Code Online (Sandbox Code Playgroud)

默认以前是WebRat但最近切换到Capybara,因此Web上旧版示例的许多代码无法正常工作.假设你也在使用Capybara ......

request.request_uri - 你想要current_url.它返回驱动程序所在页面的完整URL.这不仅仅是获取路径,所以我使用这个帮助器:

def current_path
  URI.parse(current_url).path
end
Run Code Online (Sandbox Code Playgroud)

response.should be_success - 与Capybara(以及在某种程度上,Cucumber)合作的最大挫折之一是,仅仅与用户可以看到的内容交互是彻头彻尾的热心.您无法使用Capybara 测试响应代码.相反,您应该测试用户可见的响应.重定向很容易测试; 只是断言你应该在哪个页面上.403s是一个小小的招数.在我的应用程序中,这是一个标题为"拒绝访问"的页面,所以我只测试它:

within('head title') { page.should_not have_content('Access Denied') }
Run Code Online (Sandbox Code Playgroud)

这是我如何编写一个方案来测试一个有时会重定向但不应该在其他时间重定向的链接:

Scenario: It redirects
  Given it should redirect
  When  I click "sometimes redirecting link"
  Then  I should be on the "redirected_to" page

Scenario: It does not redirect
  Given it shouldn't redirect
  When  I click "sometimes redirecting link"
  Then  <assert about what should have happened>
Run Code Online (Sandbox Code Playgroud)