LoginSignup
50
48

More than 5 years have passed since last update.

【Ruby on Rails】RSpecのdescribe/context/itの意味を理解した件

Last updated at Posted at 2018-04-23

RSpecを書くときに、describeとかitの意味を理解していなかった。
そこでdescribe、context、itに何を記述すればいいのか?を考えながらRSpec書いたら、まじでみやすくなった。

なので、describe、context、itの意味を備忘録的に本当に最低限まとめておく。

descirbe '#ここにはテスト対象を書く'  do

end

describeには、基本的にテスト対象を書く。
例えば、Userクラスのfindメソッドをテスト対象とする場合は、以下のように書く。

describe 'User' do

  describe '#find' do 

  end
end

特に、メソッドであることを明示するためにメソッド名の前に#を記載する。
また、テスト対象のメソッドに引数がある場合は、それも書いておくと親切!

describe 'User' do

  describe '#find(user_id)' do 

  end
end

次にcontext。
contextとは、テスト対象のメソッドをどういう条件で実行するかを記載してあげる。

正常系なのか?異常系なのか?と言った具合。

例えば、条件をuser_idがnullであるときを考える場合は、以下のようになる。

describe 'User' do

  describe '#find(user_id)' do 
   context 'when user_id is null' do 

   end
  end
end

contextに書く英文は、whenやwithを使うことが多い。

そして、このcontextの下に、条件を満たすような値やmockを設定してあげる。

describe 'User' do

  describe '#find(user_id)' do 
   context 'when user_id is null' do 
     #letとかbeforeとかallowはググってみてケロ
     let(:user_id) { nil } 
     let(:body) { {id: 1, name: 'ほげ太郎'} }
     before do
       allow(Hoge).to receive(:select).and_return(body.to_json) 
     end
   end
  end
end


こうすることで、context周辺を見れば、条件を満たす変数の状態などがひと目でわかる!
↑↑↑↑↑追記↑↑↑↑↑
allowはbefore句で囲まないとエラーでます!指摘してもらいました!
確かに忘れてました。

そんで最後。itにはテスト実行時の期待値を記載する。

describe 'User' do
  describe '#find(user_id)' do 
   context 'when user_id is null' do 
     let(:user_id) { nil } 
     let(:body) { {id: 1, name: 'ほげ太郎'} }

     before do
       allow(Hoge).to receive(:select).and_return(body.to_json) 
     end

     # 注:エラーが起きることを検証する場合は、returnsよりもraisesと書く方が
     # Rubyの文法的には自然かも
     it 'returns ActiveRecordNotFound' do
     end
   end
  end
end

こんな感じ。

ある程度RSpecに記載する英単語や英文は、限られてそうなので書きながら覚えてしまうのがいいかもですね。

50
48
0

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
50
48