assert_* and assert_not_* 4

Posted by pratik
on Tuesday, March 17

Not sure I like this or not, but I’m gonna give it a shot in the “real world” nevertheless.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
module AssertionExtensions
  def method_missing(method_id, *arguments, &block)
    return super unless method_id.to_s =~ /^assert_(not_)?(.*)$/
 
    method = "#{$2}?"
    object = arguments.first
 
    if $1
      arguments.each do |object|
        assert ! object.send(method), "#{method} is not false for #{object}"
      end
    else
      arguments.each do |object|
        assert object.send(method), "#{method} is not true for #{object}"
      end
    end
  end
end
 
class ActiveSupport::TestCase
  include AssertionExtensions
end

Now using this in your tests:

1
2
3
4
5
6
7
8

def test_is_admin
  # [people(:admin), people(:superuser)].each {|p| assert p.admin?}
  assert_admin people(:admin), people(:superuser)

  # assert ! people(:foo).admin?
  assert_not_admin people(:foo)
end
Comments

Leave a response

  1. Seth Thomas RasmussenMarch 17, 2009 @ 03:56 PM

    This must be that “metaprogramming” I’ve heard so much about..

  2. TomMarch 17, 2009 @ 06:07 PM

    ITYM people(:foo).should be_admin HTH

  3. lucapetteMarch 17, 2009 @ 08:01 PM

    Just another reason to like method_missing…

  4. Ryan HeathMarch 20, 2009 @ 04:55 PM

    Nice, I think I like it.

Comment