Rspec DRY:将示例应用于所有上下文

时间:2019-04-23 19:52:35

标签: ruby-on-rails rspec dry

是否可以缩短此Rspec? 我想提取it { expect { author.destroy }.to_not raise_error }行,以免在每种情况下都重复。共享示例是某种方式,但最终,它生成的代码比冗余版本以下的代码还要多。

require 'rails_helper'

RSpec.describe Author, type: :model do
  describe 'destroying' do
    context 'when no books assigned' do
      subject!(:author) { FactoryBot.create :author_with_no_books }

      it { expect { author.destroy }.to_not raise_error }
      # other examples
    end

    context 'when there are some books' do
      subject!(:author) { FactoryBot.create :author_with_books }

      it { expect { author.destroy }.to_not raise_error }
      # other examples
    end

    context 'when there are some posts' do
      subject!(:author) { FactoryBot.create :author_with_posts }

      it { expect { author.destroy }.to_not raise_error }
      # other examples
    end
  end
end

1 个答案:

答案 0 :(得分:1)

使用带有参数的shared_examples而不是abusing subject

RSpec.describe Author, type: :model do
  include FactoryBot::Syntax::Methods # you can move this to rails_helper.rb

  RSpec.shared_examples "can be destroyed" do |thing|
    it "can be destroyed" do
      expect { thing.destroy }.to_not raise_error
    end
  end

  describe 'destroying' do
    context 'without books' do
      include_examples "can be destroyed", create(:author_with_no_books)
    end

    context 'with books' do
      include_examples "can be destroyed", create(:author_with_books)
    end

    context 'with posts' do
      include_examples "can be destroyed", create(:author_with_posts)
    end
  end
end