From: Rob Biedenharn Date: 2009-02-05T09:34:40+09:00 Subject: Re: custom assertion message for unit tests On Feb 4, 2009, at 5:59 PM, Will Parsons wrote: > I'm having trouble trying to figure out how to customize an assertion > message when running unit tests. In particular, I want to check the > permissions on a file, so I have something like: > > assert_equal(0755, File.stat(test_file).mode & 0777) > > If it fails, I get a message like: > > <493> expected but was > <420>. > > and of course I would like the expected and actual permissions to be > displayed in octal rather than decimal. How can I do that? > > -- > Will Perhaps something like: $ ruby -r'test/unit' class SomeTest < Test::Unit::TestCase def setup @test_file = 'some_file' File.open(@test_file, 'w') {|f| f.write "Hello!"} end def test_bad_file_mode File.chmod(0644, @test_file) assert_equal '0755', '%#o'%[File.stat(@test_file).mode & 0777], "Mode of #{@test_file}" end def test_good_file_mode File.chmod(0755, @test_file) assert_equal '0755', '%#o'%[File.stat(@test_file).mode & 0777], "Mode of #{@test_file}" end end __END__ Loaded suite - Started F. Finished in 0.025823 seconds. 1) Failure: test_bad_file_mode(SomeTest) [-:9]: Mode of some_file. <"0755"> expected but was <"0644">. 2 tests, 2 assertions, 1 failures, 0 errors Note that I'm doing the conversion to octal myself with the '%#o' and String#% It would be better to pull this into a helper method: $ ruby -r'test/unit' class SomeTest < Test::Unit::TestCase def assert_mode(expected_mode, actual_mode, message=nil) assert_equal '%#o'%expected_mode, '%#o'%actual_mode, message end def setup @test_file = 'some_file' File.open(@test_file, 'w') {|f| f.write "Hello!"} end def test_bad_file_mode File.chmod(0644, @test_file) assert_mode 0755, File.stat(@test_file).mode & 0777, "Mode of #{@test_file}" end def test_good_file_mode File.chmod(0755, @test_file) assert_mode 0755, File.stat(@test_file).mode & 0777, "Mode of #{@test_file}" end end __END__ Loaded suite - Started F. Finished in 0.0107 seconds. 1) Failure: test_bad_file_mode(SomeTest) [-:3:in `assert_mode' -:13:in `test_bad_file_mode']: Mode of some_file. <"0755"> expected but was <"0644">. 2 tests, 2 assertions, 1 failures, 0 errors Do you really want assert File.stat(@test_file).executable? instead of a specific mode? -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com