如何在RSPEC中设置语言环境

时间:2018-08-27 13:40:14

标签: rspec locale

我是RSPEC的新手。我编写了一个名为result_spec.rb的RSPEC代码,如下所示:

describe '#grouped_scores' do
subject { result.grouped_scores }

let(:result) { create(:result, user: user) }

its(:keys) { is_expected.to eq [1] }
its([1]) { is_expected.to be_within(0.001).of(6) }
end

然后,当我在名为result.rb的模型中编写方法时,示例代码如下:

def grouped_scores
  s = 0
  if score > 10 && I18n.locale == :zh then
    s = 2
  end
  return s
end

但是,当我在本地测试RSPEC时,我一直遇到以下错误:

Failures:
1) Result#grouped_scores keys should eq [1]
 Failure/Error: its(:keys) { is_expected.to eq [1] }

   expected: [1]
        got: []

   (compared using ==)
 # ./spec/models/result_spec.rb:39:in `block (3 levels) in <top (required)>'
2) Result#grouped_personality_scores [1] should be within 0.001 of 6
 Failure/Error: its([1]) { is_expected.to be_within(0.001).of(6) }
   expected 0 to be within 0.001 of 6
 # ./spec/models/result_spec.rb:40:in `block (3 levels) in <top (required)>'

所以我在想,是否因为我没有将I18n.locale设置为“ zh”,所以没有得到值?如果是这样,如何在RSPEC中分配语言环境?还是我应该知道的其他信息来调试RSPEC中的错误?

请帮助!谢谢!

1 个答案:

答案 0 :(得分:0)

测试语言环境

# Assuming I have a LocalesController with check_for_locale action
describe LocalesController do

  after(:each) do
    I18n.locale = :en
  end

  it "should check if the locale is zh" do
    get :check_for_locale, locale: :zh
    expect(I18n.locale).to eq(:zh)
  end

  it "should check if the locale is set to default that is english" do
    get :check_for_locale
    expect(I18n.locale).to eq(:en)
  end

end

locales_controller.rb

class LocalesController < ApplicationController

  def check_for_locale

  end

end