Use rspec partial mock to write a quick executing example.
I wanted to test an error message in my class that processes test results and sends them to Rally. The problem was that I did not want to actually create a rally object and run the method to parse the results, just to test the error message.
This is what my class looks like.
class AutomationRun def send_results_to_rally @rally = RallyUtils.new(ENV['RALLY_WORKSPACE']) push_test_case_results raise("Test Case Results Were Not Parsed Correctly") if test_case_results.empty? test_case_results.each do |result| @rally.update_test_case_result(:tc_id =>result.test_case_number_from_spec_report, :build =>result.build_number, :verdict =>result.verdict, :notes => result.note.format_note) end end end
I want to skip these steps to test the error message:
- don’t instantiate RallyUtils.new we don’t need @rally for the test
- don’t parse the results so don’t call parse_test_case_results
This is what my test code looks like:
it "should raise an exception if there are not test case results" do RallyUtils.stub!(:new).and_return(nil) automation_run=AutomationRun.new automation_run.should_receive(:push_test_case_results).and_return([]) begin automation_run.send_results_to_rally rescue Exception=>e end e.message.should == "Test Case Results Were Not Parsed Correctly" end
- We use a rspec stub to intercept the new call to the RallyUtils class and return nil. We could have also returned a mock object if we wanted to execute a call on the rally class. Now we are not creating a connection to Rally
- Now it is time to new up or AutomationRun class and setup our mock expectation to skip running the real push_test_case_results method.
- automation_run.should_receive tells us to intercept the symbol or method push_test_case_results
- and_return([]) will just return an empty array
- We setup a begin rescue block to capture the Exception object returned by our expected error message
- Now we call send_results_to_rally to get our error message
- Lastly we verify that the message attribute for our error is Test Case Results Were Not Parsed Correctly
So that is it, I created a partial mock in that we are using a real automation run object but we stubbed out one of the methods. We also stubbed out the new call to rally so we don’t create a connection. Now I can focus my test on exactly the function I wanted to test, the error message.