0

I'm fairly new to using RSpec. I'm wondering what the best practice is regarding test/output readability. Here I have two examples of testing a class method. The first has straightforwardly (?) readable tests, but the output is a bit ambiguous. The second has verbose/redundant tests when read, but the output is very clear.

class StringTester
  def self.is_hello?(s)
    s == 'hello'
  end
end

RSpec.describe StringTester do
  # Tests are fairly readable in English...
  describe '::is_hello?' do
    it { expect(StringTester.is_hello?('hello')).to be_truthy }
    it { expect(StringTester.is_hello?('something else')).to be_falsey }
  end
end

# ...but the output is ambiguous without going back to look at the tests.
# Output:
# StringTester
#   ::is_hello?
#     should be truthy
#     should be falsey


RSpec.describe StringTester do
  # Tests are redundant when read in English...
  describe '::is_hello?' do
    it 'is true for "hello"' do
      expect(StringTester.is_hello?('hello')).to be_truthy
    end
    it 'is false for "something else"' do
      expect(StringTester.is_hello?('something else')).to be_falsey
    end
  end
end

# ...but the output is very straightfoward.
# Output:
# StringTester
#   ::is_hello?
#     is true for "hello"
#     is false for "something else"

So is one way considered a better practice than the other?

istrasci
  • 1,331
  • 1
  • 18
  • 40

1 Answers1

1

I would say the second form is usually preferable because the it description allows you to explain the rule that's being tested. In your code above, it only looks like duplication because this is a very simple, contrived example.

Let's say you were testing code which checks if an input is positive:

describe '#positive?' do it 'is true for numbers greater than zero' do expects(Foo.positive?(1)).to be_truthy end it 'is false for numbers less than zero' do expects(Foo.positive(-1)).to be_falsey end end

The RSpec output then becomes more readable as it is describing the overall behaviour rather than just the output for individual examples.

Andy Waite
  • 10,785
  • 4
  • 33
  • 47