Rspec DRY: применить пример ко всем контекстам - PullRequest
0 голосов
/ 23 апреля 2019

возможно ли сократить этот 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 Ответ

1 голос
/ 24 апреля 2019

Используйте 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
...