From: Brian Candler Date: 2010-05-12T19:19:52+09:00 Subject: Re: Unit Test of method calling system() - how? Martin Hansen wrote: > test "Options.parse with empty argv and existing wiki file don't raise" > do > opt_parser = Options.new > assert_nothing_raised() { opt_parser.parse([],"/foo/bar.rb") } > end if full system("print_wiki --data_in #{@wiki_path} --help") else system("print_wiki --data_in #{@wiki_path}") end raise "Failed printing wiki: #{@wiki_path}" if $? AFAICS this will always raise, since $? will never be nil. I think you want: raise ... unless $?.success? > However, the original problem remains - I really want to test the > following: > > test "Options.parse with empty argv and existing wiki output short > usage" do > opt_parser = Options.new > assert("" == opt_parser.parse([],"/foo/bar.rb")) > end > > test "Options.parse with --help in argv and existing wiki output long > usage" do > opt_parser = Options.new > assert("" == opt_parser.parse(["--help"],"/foo/bar.rb")) > end In that case you would need to collect the output from print_wiki, for example using the IO.popen code I showed before. > I am actually not interested in the invocation of print_wiki, since this > Perl script is tested - so never mind about testing the > print_usage_and_exit -> good enuf for government work... But I am > interested in testing the print_usage_full? and print_usage_short? > methods. So how to do that? Well, that's what mocking is for. You say you don't actually want to run print_usage_and_exit, so I think you want to check that it *would* have been run, with the correct arguments to do what you want. opt_parser = Options.new opt_parser.expects(:print_usage_and_exit).with() assert_nothing_raised { opt_parser.parse([], "/foo/bar.rb") } At the end of your test method, if :print_usage_and_exit wasn't called, or was called with different arguments, you'll get an error raised by the mocking framework. The awkward thing is that print_usage_and_exit might actually be called multiple times, 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 As for $0: this tends to be dangerous anyway (it is subject to truncation under various conditions). __FILE__ is safer, giving the location of the current source file, if that's usable. But otherwise I would be inclined to move this logic out into the code which calls the option parser: i.e. def parse(argv, wiki_path) @wiki_path = wiki_path ... end and then in your main bin file: opt_parser.parse(ARGV, ENV["BP_DIR"] + "/bp_usage/" + File.basename($0, ".rb") + ".wiki")) Just a suggestion. -- Posted via http://www.ruby-forum.com/.