rspec file is newer than

Posted by Jason Noble on 09/10/2009 in rspec simple_matcher custom_matcher be_newer_than |

My pair and I were working on implementing LessCSS at work this week and we ran into an interesting problem. We wanted to write RSpec tests that would figure out if the .less file was newer than the .css file, and if so provide a good error message.

We discussed this with Hosh and he suggested using a custom matcher, which we had not heard of before. In researching custom matchers, we came up with the following solution:

[ruby]
def be_newer_than(new_file, msg=nil, msg2=nil)
simple_matcher do |old_file, matcher|
old_file_mtime = File.stat(old_file).mtime
new_file_mtime = File.stat(new_file).mtime
matcher.description = "be newer than #{new_file.inspect}"
matcher.failure_message = msg || "expected #{old_file.inspect} to be newer than #{new_file.inspect}"
matcher.negative_failure_message = msg2 || "expected #{old_file.inspect} to be older than #{new_file.inspect}"

old_file_mtime >= new_file_mtime
end
[/ruby]

This allows you to do the following:

[ruby]
css_file = "site.css"
less_file = "site.less"
css_file.should be_newer_than(less_file)
[/ruby]

This will tell you if css_file is newer than the less file.

The optional arguments allow you to pass custom error messages. For example:

[ruby]
it "should be up to date" do
output = "#{css_file} is not up to date. Please run the following: "
output += "\n\t lessc #{less_file}\n\n"
css_file.should be_newer_than(less_file, output)
end
[/ruby]

Copyright © 2008-2024 Jason Noble's Technical Adventures All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.