From: Martin Hansen Date: 2010-05-12T22:29:46+09:00 Subject: Re: Unit Test of method calling system() - how? So with code: if print_usage_full? print_usage_and_exit(true) return # break for unit testing. elsif print_usage_short? print_usage_and_exit return # break for unit testing. end and test: test "Options.parse with --help in argv and existing wiki output long usage" do opt_parser = Options.new opt_parser.expects(:print_usage_and_exit).with(:full) assert( "" == opt_parser.parse(["--help"],SCRIPT_PATH) ) end I now get the following err: optparse_swapcase_seq_test.rb:183:in `block in ']: unexpected invocation: #.print_usage_and_exit(true) unsatisfied expectations: - expected exactly once, not yet invoked: #.print_usage_and_exit(:full) :o/ and I am still not sure what exactly to assert ... M Brian Candler wrote: > Martin Hansen wrote: >>> so it may be worth changing the >>> call to >>> >>> if print_usage_full? >>> print_usage_and_exit(true) >>> return # not reached except in testing >>> end >> >> This I don't understand. How can the method be called multiple times, >> and how can that be fixed by introducing a return? I do get this funky >> error: >> >> "- expected exactly once, already invoked once: >> #.print_usage_and_exit(:full)" > > Your code is: > > ... > print_usage_and_exit(true) if print_usage_full? > print_usage_and_exit if print_usage_short? > > options_default > ... > > When running normally, if you call print_usage_and_exit(true) then > inside it calls 'exit' which terminates the program. > > But if you mock out print_usage_and_exit then it will return, and > continue to the next line. So if print_usage_short? is also true, it > will call print_usage_and_exit() as well. > > I think that's what the error message is telling you. By default the > expectation set is that the method will be called exactly once, and it > was actually called more than once. (Mocha lets you override this if you > want it to be called more than once) > > I should add that I'm actually not a big fan of mocking; working out how > to get the mocking framework to do what I want distracts me from actual > programming. But in this case, it looks like the right tool for the job. -- Posted via http://www.ruby-forum.com/.