Gil*_*les 5 ruby testing rspec ruby-on-rails rspec-rails
我想测试视图以确保正确呈现错误消息。我的config.default_locale是'fr'。因此,我希望我的视图能够从我的法语区域设置文件中找到正确的 Active Record 错误消息。
describe 'book/new.html.erb' do
let(:subject) { rendered }
before do
@book = Book.create #this generates errors on my model
render
end
it { should match 'some error message in French' }
end
Run Code Online (Sandbox Code Playgroud)
当单独运行或与其他规范/视图一起运行时,此测试通过。但是当我运行完整的测试套件时,视图会呈现以下消息:translation missing: en.activerecord.errors.models.book.attributes.title.blank。
我不明白为什么它会以en语言环境呈现。我尝试使用以下命令强制区域设置:
before do
allow(I18n).to receive(:locale).and_return(:fr)
allow(I18n).to receive(:default_locale).and_return(:fr)
end
Run Code Online (Sandbox Code Playgroud)
和
before do
default_url_options[:locale] = 'fr'
end
Run Code Online (Sandbox Code Playgroud)
有人有想法吗?
这并不能直接解决您的视图规范问题,但我的建议可能会解决您的问题。
为了测试实际的错误消息,我不会使用视图规范。相反,我会使用带有shoulda-matchers 的模型规范来测试一本书是否必须有标题,并使用适当的错误消息:
describe Book do
it do
is_expected.to validate_presence_of(:title).
with_message I18n.t('activerecord.errors.models.book.attributes.title.blank')
end
end
Run Code Online (Sandbox Code Playgroud)
为了测试当用户尝试创建没有标题的书籍时是否向用户显示错误消息,我将使用Capybara的集成测试,如下所示:
feature 'Create a book' do
scenario 'without a title' do
visit new_book_path
fill_in 'title', with: ''
click_button 'Submit'
expect(page).
to have_content I18n.t('activerecord.errors.models.book.attributes.title.blank')
end
end
Run Code Online (Sandbox Code Playgroud)
在测试中使用区域设置键的优点是,如果您更改实际文本,您的测试仍然会通过。否则,如果您正在测试实际文本,则每次更改文本时都必须更新测试。
除此之外,如果翻译丢失,最好通过将以下行添加到您的 中来引发错误config/environments/test.rb:
config.action_view.raise_on_missing_translations = true
Run Code Online (Sandbox Code Playgroud)
请注意,上面的行需要 Rails 4.1 或更高版本。
如果您希望测试大量语言环境,您可以将此帮助程序添加到 RSpec 配置中,这样您就可以直接使用,t('some.locale.key')而不必总是键入I18n.t:
RSpec.configure do |config|
config.include AbstractController::Translation
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2248 次 |
| 最近记录: |