如何为所有Capybara功能设置HTTP标头

12

我使用 rspec 和 capybara。我从 HTTP 标头中设置语言环境,代码如下:

  before_filter :set_locale

  def extract_locale_from_accept_language_header
    request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
  end

  def set_locale
    return I18n.locale = current_user.locale if user_signed_in?
    I18n.locale = extract_locale_from_accept_language_header || I18n.default_locale
  end

当我运行我的功能测试时,我会得到错误信息:“undefined method 'scan' for NilClass”。显然,capybara没有设置http头。

我如何为所有的功能设置http头或通过其他方式避免这个问题?


也许这可以给你一些启发:https://gist.github.com/raul/717819 - apneadiving
2个回答

13

根据您的浏览器驱动程序,您可以像这样全局设置标题:

  Capybara.current_session.driver.headers = { 'Accept-Language' => 'de' }
  Capybara.current_session.driver.header('Accept-Language', 'de')

它似乎不能“粘”在所有功能和场景上。有什么想法为什么? - Aurélien Bénel
在每个功能文件中都包含的 spec_helper.rb 文件中。 - Aurélien Bénel
3
请将其添加到配置文件中的每个“before:each”块中。 - phoet
可以了,非常感谢。以后需要的话,这里有相关的 RSpec 语法 - Aurélien Bénel
如何只针对一个测试进行操作? - Eddie
显示剩余2条评论

9

1
只有使用WebKit驱动程序,您才能确信它可以正常工作。 - mzedeler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接