8
4

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 5 years have passed since last update.

RspecでSubjectを複数回実行する方法

Last updated at Posted at 2018-07-05

背景

モデルの操作などで、冪等性をテストしたいけどベストプラクティスがわからない。

例えば

model_spec.rb

describe Model, type: :model do
  describe '.do_something' do

    subject { Model.do_something }

    context 'execute twice' do
       it 'not duplicate records' do
         subject
         expect{ subject }.to change{ Model.count }.by(0)
       end
    end

  end
end

↑これだと、
subjectはひとつのexample内ではメモ化されるので複数回実行されない。

解決策

1. subjectの中身をexample内にべた書きする

model_spec.rb

describe Model, type: :model do
  describe '.do_something' do

    subject { Model.do_something }

    context 'execute twice' do
       it 'not duplicate records' do
         Model.do_something
         expect{ subject }.to change{ Model.count }.by(0)
       end
    end

  end
end

ただ、見通しも悪くなるし
subjectの中身が複数行の場合や、3回以上実行したい場合に行数が増えすぎる問題がある

## 2. subjectの中身をメソッドに定義する

model_spec.rb

describe Model, type: :model do
  describe '.do_something' do

    subject { model_do_something }

    def model_do_something
      Model.do_something
    end

    context 'execute several times' do
       it 'not duplicate records' do
         model_do_something
         model_do_something
         model_do_something
         model_do_something
         expect{ subject }.to change{ Model.count }.by(0)
       end
    end

  end
end

これがベストな気がする。

もっとスマートなやり方があったら教えてください

8
4
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
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?