LoginSignup
10
6

More than 1 year has passed since last update.

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

Last updated at Posted at 2015-12-14

問題

なぜか should ではテストが成功し。
is_expected では落ちる spec を見つけた。

is_expected は should のエイリアスではないのだろうか?

結論

is_expected を書いたテストでは、 Rspec 3 の処理順が適用されるようになる。

そして。

Rspec 2 では let => subject の順に。
Rspec 3 では subject => let の順に。

逆の順番で処理が走る。これが理由だった。

問題になることは少ないと思うが。
この順序に依存したテストを書いているときは注意だ。

(依存しないようにテストを変えたほうが良い)

検証コード

let と subject が走った時に、それぞれコンソールに標準出力してみる。

test_spec.rb
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 { is_expected.to 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"

補足

Rspec 2 でも subject! を使えば、subject を先に走らせることも出来る。

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

Rspec 3 でも let! を使えば、 let を先に走らせることも出来る。

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

しかし、この順番に依存しないテストを書こう。

環境

  • rspec-rails 3.4.0

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

メンター受付

10
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
6