0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【RSpec】shared_examplesを使ってリファクタリング

Last updated at Posted at 2021-10-27

##環境
Ruby 3.0.2
Rails 6.1.4.1

##リファクタリング前

yearの値が複数に条件分岐するテスト。
コードはほぼ同じでyearの値とメソッド実行した返り値が異なるだけなので
shared_examplesを使ってコードをまとめたい。

spec.rb
describe '#get_post_count_for_year' do
  context 'yearが0のとき' do
     let!(:year) { 0 }
     it '10を返す' do
        expect(Post.get_post_count_for_year(year)).to eq 10
     end
  end
  context 'yearが1のとき' do
     let!(:year) { 1 }
     it '20を返す' do
        expect(Post.get_post_count_for_year(year)).to eq 20
     end
  end
...
end

##リファクタリング後

spec/support/contexts/post_count.rb
RSpec.shared_examples :post_count do
  it '正しい値を返すこと' do
    expect(Post.get_post_count_for_year(year)).to eq result
  end
end
spec.rb
describe '#get_post_count_for_year' do
  context 'yearが0のとき' do
    let!(:result) { 10 }
    it_behaves_like :post_count
  end
  context 'yearが1のとき' do
    let!(:result) { 20 }
    it_behaves_like :post_count
  end
...
end

##参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?