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

将shared_examples与参数一起使用,而不是滥用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

最新更新