Best practice RSpec example formatting for a multiple "simple" expectations

Viewed 33

I'm tryna improve my RSpec skills following the bests practices. I have a simple method is_multiple_of_3_or_5? and I'm implementing a test for it using simple testing values. My first approach was:

describe '#is_multiple_of_3_or_5?' do
  context "when input is multiple of 3 or 5" do
    expect(is_multiple_of_3_or_5?(3)).to be true
    expect(is_multiple_of_3_or_5?(5)).to be true
    expect(is_multiple_of_3_or_5?(51)).to be true
    expect(is_multiple_of_3_or_5?(45)).to be true
  end
end

I like it because it's very short and the test cases are simple, so no need to complicate it.. But I've read in the RSpec style guide that it should be only one expectation per example. So I refactored in 2 other ways:

One it per example:

describe '#is_multiple_of_3_or_5?' do
  context 'when input is multiple of 3 or 5' do
    it "is true for 3" do
      expect(is_multiple_of_3_or_5?(3)).to be true
    end

    it "is true for 5" do
      expect(is_multiple_of_3_or_5?(5)).to be true
    end

    it "is true for 51" do
      expect(is_multiple_of_3_or_5?(51)).to be true
    end

    it "is true for 45" do
      expect(is_multiple_of_3_or_5?(45)).to be true
    end
  end
end

Drying up with a subject block

describe '#is_multiple_of_3_or_5?' do
  context 'when input is multiple of 3 or 5' do
    subject { is_multiple_of_3_or_5?(input) }

    context 'when input is 3' do
      let(:input) { 3 }
      it { is_expected.to be true }
    end

    context 'when input is 5' do
      let(:input) { 5 }
      it { is_expected.to be true }
    end

    context 'when input is 51' do
      let(:input) { 51 }
      it { is_expected.to be true }
    end

    context 'when input is 45' do
      let(:input) { 45 }
      it { is_expected.to be true }
    end
  end
end

So I have 2 questions:

  • In the case of theses 2 last versions, the test became really bigger, is it really worth it? Considering that the values tested are simple integers?
  • Which one of these 2 versions are better formatted?

Thank you for anyone who could help me take better perspective on RSpec!

0 Answers
Related