RSpec – Reusing examples

A good practice while writing RSpec tests is to reuse similar examples to make the tests DRYer and easier to read and understand.

Create a shared_examples_for block with all the reused examples and include the block with it_behaves_like where you want to use the similar examples.


describe ".trigger_action"
  let(:subject) { User.trigger_action }

  shared_examples_for "email_sent" do
    it "sends an email" do
      expect(ActionMailer::Base.deliveries).not_to be_empty
    end
  end

  context "when valid" do
    it "is true" do
      expect(subject).to be_true
    end

    it_behaves_like "email_sent"
  end

  context "when invalid" do
    it "is false" do
      expect(subject).to be_false
    end

    it_behaves_like "email_sent"
  end
end