Search code examples
rubyrspectestunitruby-1.8.7

Idiomatic Test::Unit equivalent of expect {}.to change {}.by(x)


Right now, I am simply using assert_equal twice - before and after the execution, and it does not hurt much. But I have used RSpec before and liked the readability of the expect{}.to change idiom. I cannot simply use RSpec in this project - not my project, not my stack.

Is there is a more idiomatic way to express an expected change/delta with Test::Unit?

Thank you.

I am working with Ruby 1.8.7


Solution

  • To accomplish assert_change with test unit, you can roll your own.

    Here's example code to get you started. Adjust it for your preferences.

    def assert_change valuer, delta, changer, message = nil
      expect = valuer.call + delta
      changer.call
      actual = valuer.call
      assert_equal expect, actual, message
    end
    

    Usage:

    @x = 123
    
    def foo
      @x += 456
    end
    
    assert_change(lambda{@x}, 456, lambda{foo})