DEV Community

Vasily Polovnyov
Vasily Polovnyov

Posted on

RSpec: too much going on in `expect`

Sometimes you may see this in tests:

expect(described_class.new(at: Time.new(2019, 7, 7, 9, 15)).to_human).to eq "9:15"
Enter fullscreen mode Exit fullscreen mode

Line turns out to be too long, Rubocop detects style violation, developer "fixes" it:

expect(
  described_class.new(at: Time.new(2019, 7, 7, 9, 15)).to_human
).to eq "9:00"
Enter fullscreen mode Exit fullscreen mode

The symptoms are cured, but the disease remains: there is too much going on in expect(). Let's introduce some explaining variables:

nine_in_the_morning = Time.new(2019, 7, 7, 9, 15)
alarm = described_class.new(at: nine_in_the_morning)

expect(alarm.to_human).to eq "9:15"
Enter fullscreen mode Exit fullscreen mode

And if we remove the details that are irrelevant to the test - year, month and day - it gets even better:

nine_in_the_morning = Time.now.change(hour: 9, min: 15)
alarm = described_class.new(at: nine_in_the_morning)

expect(alarm.to_human).to eq "9:15"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)