ruby-on-rails - 由于错误的默认语言环境,我的 Rails 应用程序规范随机失败

标签 ruby-on-rails ruby rspec rspec-rails rails-i18n

有时,我的 Rails 应用程序的某些规范似乎会随机失败,因为突然英语不再是默认语言,而是德语:

   expected: "Project test customer - Project test name (Audit, Access for all, 2015-06-15).pdf"
        got: "Project test customer - Project test name (Audit, Zugang für alle, 2015-06-15).pdf"

如您所见,“人人享有”部分突然变成了“Zugang für alle”。我在谷歌上搜索了一个解决方案,似乎 I18n.locale is a global object, so when it's changed in a spec, it persists .

问题并不总是发生,但我可以在指定种子时重现它,如下所示:rspec --seed 51012。因此,在其他规范之前(或之后)执行规范似乎确实存在一些问题。

我有一个功能规范来测试是否可以更改语言环境,如下所示:

it 'offers contents in german' do
  visit root_path(locale: :de)

  expect(page).to have_content 'Willkommen'
end

我怀疑这可能是有问题的规范,当它提前运行时,它会对其他规范产生影响。

我希望我可以通过将规范中的语言设置回默认值来解决这个问题:

it 'offers contents in german' do
  visit root_path(locale: :de)

  expect(page).to have_content 'Willkommen'

  I18n.locale = :en
end

没用,这个也没用:

it 'offers contents in german' do
  visit root_path(locale: :de)

  expect(page).to have_content 'Willkommen'
  visit root_path(locale: :en)
end

我现在有点不知所措。我如何调试这种情况,以便我确定问题的根源并修复它(或至少解决它)?

更新

使用 Dave 的答案 (rspec --bisect) 我发现了问题。

# application_controller_spec.rb
describe ApplicationController do
  controller(ApplicationController) do
    def index
      render text: 'Hello World'
    end
  end

  describe 'locale parameter' do
    it 'is set to english when not available in the request' do
      get :index
      expect(I18n.locale).to eq :en
    end

    it 'can be set through the request' do
      get :index, locale: :de
      expect(I18n.locale).to eq :de
    end
  end
end

根据这些规范的运行顺序,以下规范的区域设置为 :de:en

我用 BoraMa 建议的代码片段修复了它:

RSpec.configure do |config|
  config.after(:each) { I18n.locale = :en }
end

我仍然有点惊讶 RSpec/Rails 不会自己自动执行此操作...

最佳答案

注释掉您怀疑的规范并运行 rspec --seed 51012。如果通过,您就知道罪魁祸首了。

如果不是,这看起来像是 rspec --bisect 的工作。做

rspec --seed 51012 --bisect

并让 RSpec 找到重现失败的最小示例集(可能是 2 个)。然后您可以决定如何处理罪魁祸首。

此功能在 RSpec 3.3 中可用,在 RSpec 3.4 中更好。更多信息:https://relishapp.com/rspec/rspec-core/docs/command-line/bisect

关于ruby-on-rails - 由于错误的默认语言环境,我的 Rails 应用程序规范随机失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36040661/

相关文章:

ruby-on-rails - 雾警告和 AWS : unable to load the 'unf' gem

ruby-on-rails - 自定义验证 :on => :create not working

ruby-on-rails - RSpec Devise sign_in 未在 Controller 中设置 current_user

ruby - 有没有办法在 RSpec 中取消 stub ?

ruby - 代码实际上没有在 RSpec 中断言?

ruby - 如何检查我的主题是否引发异常?

ruby-on-rails - 无法推送到 Heroku:Sprockets::FileNotFound:找不到 application.css

ruby-on-rails - 使用 RSpec 的开源 Rails 项目

ruby-on-rails - 如何翻译 rails 中的模型名称以获取 locale yml 文件中的错误消息?

ruby-on-rails - 我如何邀请用户(使用 devise_invitable)并在邀请过程中填充其他字段?