Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save purinkle/c827b69773291c64e387f5d5f0214f87 to your computer and use it in GitHub Desktop.
Save purinkle/c827b69773291c64e387f5d5f0214f87 to your computer and use it in GitHub Desktop.
Naming Validations After Predicate Methods

Naming Validations After Predicate Methods

RSpec has many fantastic built-in matchers. One of my favourites is the predicate matcher. Not only does this matcher help make my tests more readable, but it also helps me design the name of my method.

You might decide to have a method like the following.

class SomeClass
  # …
  
  def is_disabled?
    # …
  end

  # …
end

With this implementation, the following test does not read as well as it could.

RSpec.describe SomeClass do
  describe "#is_disabled?" do
    context "when something" do
      it "is true" do
        object = SomeClass.new

        expect(object.is_disabled).to be(true)
      end
    end
  end
end

Now, this reads kind of okay, but imagine if it could read something like this. I admit there will be a better way to write this test, but that's a tale for another day.

RSpec.describe SomeClass do
  describe "#is_disabled?" do
    context "when something" do
      it "is true" do
        object = SomeClass.new

        expect(object).to be_disabled
      end
    end
  end
end

For this test to work, we need to rewrite our original implementation.

class SomeClass
  # …
  
  def disabled?
    # …
  end

  # …
end

You may argue that there is little difference between these two names. In the grand scheme of things, it might not even matter. This flow is an example of TDD that shows us how to make our code more descriptive. The above is not a hard and fast rule. With everything, your mileage may vary. In the end, this is how I design my code. I wanted to share it with you.

I hope that this tip is helpful to you. I'd love to hear how you'd write this test. I'm always open to new ideas.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment