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

问题描述 投票:0回答:1

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

ruby-on-rails rspec dry
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.