I’m writing a gem that can be used both with and without rails. In a few places I use code like
path = Rails.root if defined?(::Rails)
and I want to test this logic with rspec. I have tried stubbing it like
stub(:"::Rails").should_receive(:root).and_return("/rails")
but this does not make defined?(::Rails) evaluate to true.
Even if
defined?(::Rails)is evaluated to true, you still need aRailsobject to inject the method stub. There might be several ways to do this, following is a example of my preferred approach:I’m not sure if it works on all ruby version, but at least it can work on Ruby 1.9.x.