Posted at

Subject and let run in reverse order for Rspec | should and is_expected


The test should succeed for some reason. In the is_expected I found a falling spec.

Isn't is_expected an alias for should?


In the test where is_expected is written, the processing order of Rspec 3 will be applied.


In Rspec 2 in the order of let => subject. In Rspec 3 order of subject => let.

Processing runs in the reverse order. This is the reason.

I think that there is little to be a problem. Be careful when writing tests that depend on this order.

(It is better to change the test not to depend on it)

verification code

When let and subject run, try standard output to the console respectively.

 require 'spec_helper' describe do subject { p 'SUBJECT'; 'example'; } let(:example) { p 'LET'; 'example'; } context 'when Rspec 2' do it { should eq example } end context 'when Rspec 3' do it { eq example } end end 

$ rspec -fd test_spec.rb


  when Rspec 2 "LET" "SUBJECT" should eq "example" when Rspec 3 "SUBJECT" "LET" should eq "example" 


With Rspec 2 you can also use subject! To run the subject first.

  subject! { p 'SUBJECT'; 'example'; } let(:example) { p 'LET'; 'example'; } 

With Rspec 3 you can also use let! To let let run first.

  subject { p 'SUBJECT'; 'example'; } let!(:example) { p 'LET'; 'example'; } 

But let's write a test that does not depend on this order.


  • rspec-rails 3.4.0

Original by

Rspec | should と is_expected では subject と let が逆の順番で走る


About this translattion