A small DSL to write meaningful assertions on your test/unit tests.
require "expectacular" class TestFoo < Test::Unit::TestCase include Expectacular::TestCaseMethods def test_obviousness expect(1).to == 1
expect(5).to.be > 3 expect(nil).to.be_nil expect(5).not_to == 4
end end
Including Expectacular::TestCaseMethods
will add your test cases a single method: expect
, which takes any object as an argument and returns an Expectacular::Expectation
in return. You can do assertions on expectations, by calling the methods Expectation#to
and Expectation#not_to
.
expect(1).to == 1 expect(3).not_to == 0
to
and not_to
return an Assertion
. In its context you can call several methods to test the behavior of your objects.
Expectacular comes with some assertions bundled:
-
Predicates (
be_foo
to check thatfoo?
returns true) -
be_a(Foo)
to test ancestorship (is_a?(Foo)
)
Whenever you call a method that is not one of the above, the method (and any arguments) get forwared to the object in which you set the expectation, and the result is treated as the assertion (if it returns true the test is considered to pass, if it returns false it considers the assertion to fail – unless you are using not_to
, in which case it’s the other way around.)
For example, Expectacular doesn’t define any operator assertions, those are forwarded to the object you’re setting expectations on. So the following:
expect(foo).to =~ /bar/ expect(foo).not_to == "bars"
Just calls foo =~ /bar/
and !(foo == "bars")
and makes an assertion for each of those.
module MyAwesomeAssertion THRESHOLD = 10_000 def be_very_awesome assert(object.awesomeness >= THRESHOLD,
“Expected #{object} to be very awesome”)
end end Expectacular::Assertion.add MyAwesomeAssertion expect(foo).to.be_very_awesome
Assertions have access to the following two methods:
object
-
which returns the object on which you’re setting the expectation.
assert
-
which takes a boolean value and a failure message.
You can also pass a block to Assertion.add
with the method definitions, so the above example could also be written as:
Expectacular::Assertion.add do THRESHOLD = 10_000 def be_very_awesome assert(object.awesomeness >= THRESHOLD, "Expected #{object} to be very awesome") end end expect(foo).to.be_very_awesome
Mostly, as an experiment, also, I usually don’t like libraries that mess around with core classes, so this one doesn’t :)
Thanks to Daniel Cadenas (github) for design and syntax ideas.
- Author
-
Nicolás Sanguinetti (github)
- License
-
MIT. See attached LICENSE file for details.