DEV Community

loading...

Please don't test attr_reader, attr_writer, or attr_accessor

vasily profile image Vasily Polovnyov ・1 min read

Sometimes I see code like this:

class Alarm
  attr_reader :at

  def initialize(at: )
    @at = at
  end

  def snooze
    # ...
  end
end

RSpec.describe Alarm do
  describe "#at" do
    it "returns alarm time" do
      time = Time.now
      alarm = described_class.new(at: time)

      expect(alarm.at).to eq time
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

This is a useless test. First, we are testing a standard library, a thing that already has its own tests. Why does it need more tests?

Secondly, we are testing trivial behavior.

Third, we will indirectly check the getter (Alarm#at) in other tests:

describe "#snooze" do
  it "snoozes alarm for nine minutes" do
    # ...

    expect { alarm.snooze }.to change { alarm.at }.by(9.minutes)
  end
end
Enter fullscreen mode Exit fullscreen mode

P. S. PROTIP: if the attr_reader is only needed by the object itself, it'd better to make it private:

private

attr_reader :repeat
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide