9

I have a problem understanding the usefulness of assert_predicate in MiniTest. How is it different from assert_equal? When would one want to use this assertion? I have came across it many times but did not really get its exact meaning.

Drenmi
  • 8,492
  • 4
  • 42
  • 51
delpha
  • 931
  • 1
  • 8
  • 23
  • 1
    `assert_equal` would result in a super-useless message on failure, something along the lines of "expected true to equal true, but got false instead". – Sergio Tulentsev Oct 06 '15 at 11:29
  • 1
    The only use is a better message on the assertion failing. Which is really the only use of all the extra `assert_*` methods -- otherwise really all you need is the single `assert` method. It's failure messages just aren't too useful. – jrochkind Oct 06 '15 at 16:14

2 Answers2

16

assert_equal checks to see whether the expected and actual values are equal:

assert_equal "Bender", robot.name

assert_predicate calls the named method on your target object and passes if the result is truthy:

assert_predicate robot, :bender?

You could just as easily write this test as:

assert robot.bender?

But assert_predicate can be a little more expressive in some situations and can be a little nicer when checking multiple predicate conditions:

roles = %i(admin? publisher? operator?)
roles.each {|role| assert_predicate user, role }
Chris Kottom
  • 1,249
  • 10
  • 11
4

The documentation for the method itself may answer your question:

For testing with predicates. Eg:

assert_predicate str, :empty?

This is really meant for specs and is front-ended by assert_operator:

str.must_be :empty?

That suggests that the reason is to support .must_be calls rather than providing any specific benefit over assert_equal or assert.

Shadwell
  • 34,314
  • 14
  • 94
  • 99