More mock test samples
Here are two more examples of what might become my style for writing tests that use mocks. They add a “because” clause that separates what comes into the mock from what comes out of it.
def test_checker_checks_again_after_grace_period_in_case_of_error
checker = testable_checker(:grace_period => 32.minutes)
during {
checker.check(”url”)
}.behold! {
@network.will_receive(:ok?).with(”url”)
and_then @timesink.will_receive(:sleep_for).with(32.minutes)
and_then @network.will_receive(:ok?).with(”url”)
but @listener.will_not_receive(:inform)
}.because {
@network.returned(false).from(:ok?)
but_then @network.returned(true).from(:ok?)
}
end
As before, the test first describes the activity of interest in a “during” clause. The point of the test is how the object poked in the “during” clause pokes the rest of the system. That’s in the “behold!” clause. The next question is the connection between the two: why did the object do what it did? There’s a good chance you know why from the name of the test and from reading previous tests (which I tend to arrange in a tutorial sequence). If not, you can dive into the “because” clause, which details how the rest of the system responded to the poking.
def test_checker_finally_tells_the_listener
checker = testable_checker
during {
checker.check(”url”)
}.behold! {
@listener.will_receive(:inform).with(/url is down/)
}.because {
@network.returned(false).from(:ok?)
and_then @network.returned(false).from(:ok?)
}
end