DEV Community

Vasily Polovnyov
Vasily Polovnyov

Posted on

3

Please don't test attr_reader, attr_writer, or attr_accessor

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →