How to set up locale in RSPEC

Viewed 5018

I am new to RSPEC. I have wrote a RSPEC code named result_spec.rb as below:

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

Then when I wrote the method in the model named result.rb, the sample code is as below:

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

However when I test RSPEC in local, I kept getting below error:

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)>'

So I was wondering, is it because I didn't setup the I18n.locale as "zh", therefore it didn't get the value? If so, how to assign locale in RSPEC? Or is there anything else I should know to debug the error in RSPEC?

Please help! Thanks!!

1 Answers

Testing locale

# 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
Related