How to set language in RSpec View examples
I want to test the view to make sure the error messages are displayed correctly. My config.default_locale
- 'fr'
. So, I expect my opinion to find the correct Active Record error message from my French locale file.
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
This test passes when executed in isolation or with other specifications / views. But when I run the full test suite, the view receives a message with the message translation missing: en.activerecord.errors.models.book.attributes.title.blank
.
I don't understand why it is displayed with locale en
. I tried to force the locale:
before do
allow(I18n).to receive(:locale).and_return(:fr)
allow(I18n).to receive(:default_locale).and_return(:fr)
end
and
before do
default_url_options[:locale] = 'fr'
end
Does anyone have any ideas?
source to share
This does not directly address your problem with your view spec, but what I suggest could potentially solve your problem.
To check the actual error message, I would not use the view specification. Instead, I would use the Model specification with shoulda-matchers to check that the book should have a title and that the appropriate error message is being used:
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
To test that the error message is displayed to the user when trying to create a book without a title, I would use a Capybara integration test that looks something like this:
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
The advantage of using the locale key in a test is that if you ever change the actual text, your tests will still pass. Otherwise, if you were testing the actual text, you would have to update your tests every time you changed the text.
In addition to this, it is also a good idea to raise the error in case of missing translation by adding the following line to config/environments/test.rb
:
config.action_view.raise_on_missing_translations = true
Note that this line requires Rails 4.1 or higher.
If you plan on testing multiple locales, you can add this helper to your RSpec config so you can just use t('some.locale.key')
instead of always typing I18n.t
:
RSpec.configure do |config|
config.include AbstractController::Translation
end
source to share