Daniel Kaplan
Daniel Kaplan

Reputation: 67420

In RSpec, how do I print a custom message when "expect to be true" fails?

I'm using RSpec 3.2.0 and I have this test:

  it "has a webhook_payload method" do
    Project.subclasses.each { |project_class|
      expect(project_class.method_defined? :webhook_payload).to be true, "#{project_class} is a Project subclass that does not have a required 'webhook_payload' method defined."
    }
  end

When I run this, it gives me this error:

 Failure/Error: expect(project_class.method_defined? :webhook_payload).to be true, "#{project_class} is a Project subclass that does not have a required 'webhook_payload' method defined."
 ArgumentError:
   wrong number of arguments (2 for 1)

I found this documentation on how to use custom error messages, and unless I have a typo, I feel like I'm following the instructions correctly: https://www.relishapp.com/rspec/rspec-expectations/v/3-2/docs/customized-message

How do I print a custom message when this test fails?

Also, I'm very new to ruby and rspec. If there's a more idiomatic way to write this test, please let me know.

Upvotes: 2

Views: 2682

Answers (2)

Dylan Markow
Dylan Markow

Reputation: 124429

It thinks your message is a second argument to the be method, instead of to the to method.

Wrap true in parentheses and it should work, or just use be_true as the other answer suggests.

expect(project_class.method_defined? :webhook_payload).to be(true), "#{project_class} is a Project subclass that does not have a required 'webhook_payload' method defined."

Upvotes: 7

Alex Pan
Alex Pan

Reputation: 4571

It should be be_true

it "has a webhook_payload method" do
    Project.subclasses.each { |project_class|
        expect(project_class.method_defined? :webhook_payload).to be_true, "#{project_class} is a Project subclass that does not have a required 'webhook_payload' method defined."
    }
end

Upvotes: 2

Related Questions