Jos*_*eim 10 ruby rspec ruby-on-rails 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"
Run Code Online (Sandbox Code Playgroud)
可以看出,"人人享有"这一部分突然间是"Zugangfüralle".我搜索了一个解决方案,它似乎I18n.locale
是一个全局对象,所以当它在规范中发生变化时,它会持续存在.
问题并不总是发生,但我可以在指定这样的种子时重现它:rspec --seed 51012
.因此,在某些其他规范之前(或之后)执行规范似乎确实存在一些问题.
我有一个功能规范,测试是否可以更改语言环境,如下所示:
it 'offers contents in german' do
visit root_path(locale: :de)
expect(page).to have_content 'Willkommen'
end
Run Code Online (Sandbox Code Playgroud)
我怀疑这可能是有问题的规范,当它提前运行时,它会影响其他规格.
我希望我可以通过将规范中的语言设置回默认值来解决它,如下所示:
it 'offers contents in german' do
visit root_path(locale: :de)
expect(page).to have_content 'Willkommen'
I18n.locale = :en
end
Run Code Online (Sandbox Code Playgroud)
没工作,这个也没有:
it 'offers contents in german' do
visit root_path(locale: :de)
expect(page).to have_content 'Willkommen'
visit root_path(locale: :en)
end
Run Code Online (Sandbox Code Playgroud)
我现在有点无能为力了.我怎么能调试这种情况,所以我肯定找到问题的根源并修复它(或者至少解决它)?
更新
使用戴夫的答案(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
Run Code Online (Sandbox Code Playgroud)
根据运行这些规范的顺序,区域设置被设置为:de
或:en
用于以下规范.
我用BoraMa建议的代码片段修复了它:
RSpec.configure do |config|
config.after(:each) { I18n.locale = :en }
end
Run Code Online (Sandbox Code Playgroud)
我仍然有点惊讶RSpec/Rails不会自动执行此操作...
注释掉您怀疑并运行的规范rspec --seed 51012
。如果通过了,您就知道罪魁祸首。
如果没有,这似乎是的工作rspec --bisect
。做
rspec --seed 51012 --bisect
Run Code Online (Sandbox Code Playgroud)
并让RSpec找到可重现故障的最少示例集(大概2个)。然后,您可以决定如何处理罪魁祸首。
RSpec 3.3中提供了此功能,RSpec 3.4中提供了更好的功能。此处更多内容:https://relishapp.com/rspec/rspec-core/docs/command-line/bisect
归档时间: |
|
查看次数: |
1203 次 |
最近记录: |