【问题标题】:How to set the locale in RSpec View Examples如何在 RSpec 查看示例中设置语言环境
【发布时间】:2015-01-04 17:31:59
【问题描述】:

我想测试视图以确保正确呈现错误消息。我的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

此测试在单独运行或与其他规范/视图一起运行时通过。但是当我运行完整的测试套件时,视图会显示以下消息: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

before do
  default_url_options[:locale] = 'fr'
end

有人有想法吗?

【问题讨论】:

  • 了解您使用的 RSpec 和 Rails 版本会很有帮助。

标签: ruby-on-rails ruby testing rspec rspec-rails


【解决方案1】:

这并不能直接解决您的视图规范问题,但我的建议可能会解决您的问题。

为了测试实际的错误信息,我不会使用视图规范。相反,我会使用带有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

为了测试在用户尝试创建没有标题的图书时是否向用户显示错误消息,我将使用带有 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

在测试中使用 locale 键的好处是,如果您更改了实际文本,您的测试仍然可以通过。否则,如果您要测试实际文本,则每次更改文本时都必须更新测试。

除此之外,在您的config/environments/test.rb 中添加以下行来引发错误也是一个好主意,以防翻译丢失:

config.action_view.raise_on_missing_translations = true

请注意,以上行需要 Rails 4.1 或更高版本。

如果您希望测试很多语言环境,您可以将此帮助程序添加到您的 RSpec 配置中,这样您就可以只使用 t('some.locale.key') 而不必总是输入 I18n.t

RSpec.configure do |config|
  config.include AbstractController::Translation
end

【讨论】:

    猜你喜欢
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 2014-05-29
    • 2014-01-01
    • 2019-08-27
    • 2019-08-27
    • 2011-01-24
    相关资源
    最近更新 更多