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

Rspec DRY: apply example to all contexts

是否可以缩短这个 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

使用shared_examples with a parameter instead of 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