Mocking Kernel Backticks with RSpec
February 24 2011 14:00 CET
RSpec is a great tool to test your code. I use it almost exclusively now for my Ruby projects.
Using mock’s in your test allows you to limit testing to the actual class in question and not eg. the Rails framework or other which is already sports a huge test suite.
Also, when utilizing system calls it allows you to make your specs platform independent since the system commands might vary from eg. OSX to Linux.
However, mocking Ruby’s backticks might be a little confusing since you have to mock the method on the instance of the current object and not Kernel#`.
Here is a small example:
user_spec.rb
it "should do some system call" do
user = User.find(42)
user.should_receive(:`).with("whoami").and_return("mmr")
user.system_username.should == "mmr"
end