Wednesday, May 11, 2011

Cucumber with using Rspec should_receive

I recently came across a case where I wanted to use a should_receive test in cucumber. The basic idea is that I was attempting to prevent Apache library code from calling out to the system, while simultaneously testing that the correct function was actually called. In Rspec (which backs cucumber in my setup) it is simply:



At the end of the test if restart has not been called then the entire test fails. Because of the way that cucumber works with rspec 1.3 (rails 2.x, which is required by the project) registering a should_receive has no effect (seems this is fixed in the cucumber/rspec versions for rails 3). Even if it were to work it would mean putting a Then before the When or putting a test in a Given. To me that just seems wrong.



What I had to do to simulate a should_receive but still maintain the flow of the scenario was break it up so that I stub the function and when that function is called I set a flag. Later I test that the flag is set.



The step that sets the flag is Apache can restart and the one that tests is Apache should restart. Here are the step definitions: