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 1 year has passed since last update.

RSpec長くなりがちなので短くしたい it_behaves_like

Posted at

背景

Rspecで条件が一部違うが比べるところは大体同じみたいなテストが多かった

そこで it_behaves_like を使う

用途

テストのit部分を使いまわす

使用例

it_behaves_like使う前
describe '仕事する' do
  subject { instance.test_suru_method }

  let!(:instance){ Factory.no_yatu }
  let(:target){ Factory.no_yatu }

  context 'conditionsが良いとき' do
    let(:conditions){ "good" }

    it '仕事すること' do
      is_expected
      expect(instance.published).to eq true
      expect(instance.work).to eq (target.work)
      expect(instance.conditions).to eq conditions
    end
  end

  context 'conditionsが悪いとき' do
    let(:conditions){ "bad" }

    it '仕事すること' do
      is_expected
      expect(instance.published).to eq true
      expect(instance.work).to eq (target.work)
      expect(instance.conditions).to eq conditions
    end
  end

  context 'conditionsが絶好調のとき' do
    let(:conditions){ "best" }

    it '仕事すること' do
      is_expected
      expect(instance.published).to eq true
      expect(instance.work).to eq (target.work)
      expect(instance.conditions).to eq conditions
    end
  end

  context 'conditionsが絶不調のとき' do
    let(:conditions){ "worst" }

    it '仕事すること' do
      is_expected
      expect(instance.published).to eq true
      expect(instance.work).to eq (target.work)
      expect(instance.conditions).to eq conditions
    end
  end
end
it_behaves_like使った後
  describe '仕事する' do
    subject { instance.test_suru_method(conditions) }

    let!(:instance){ Factory.no_yatu }
    let(:target){ Factory.no_yatu }

    shared_examples_for '仕事すること' do
      it do
        is_expected
        expect(instance.published).to eq true
        expect(instance.work).to eq (target.work)
        expect(instance.conditions).to eq conditions
      end
    end

    context 'conditionsが良いとき' do
      let(:conditions){ "good" }
      it_behaves_like '仕事すること'
    end

    context 'conditionsが悪いとき' do
      let(:conditions){ "bad" }
      it_behaves_like '仕事すること'
    end

    context 'conditionsが絶好調のとき' do
      let(:conditions){ "best" }
      it_behaves_like '仕事すること'
    end

    context 'conditionsが絶不調のとき' do
      let(:conditions){ "worst" }
      it_behaves_like '仕事すること'
    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?