I've got code that only needs to run on a certain version of ActiveRecord (a workaround for a bug on old AR libraries). This code tests the values of ActiveRecord::VERSION constants to see if it needs to be run.
Is there a way to mock out those constants in rspec so I can test that code path without relying on having the right ActiveRecord gem installed on the test machine?
I ended up writing a helper method to let me override constants while executing a block of code:
def with_constants(constants, &block)
constants.each do |constant, val|
Object.const_set(constant, val)
end
block.call
constants.each do |constant, val|
Object.send(:remove_const, constant)
end
end
After putting this code in your spec_helper.rb file, it can be used as follows:
with_constants :RAILS_ROOT => "bar", :RAILS_ENV => "test" do
code goes here ...
end
Hope this works for you.
With RSpec 2.11, constant stubbing is supported out of the box with stub_const
:
describe "stub_const" do
it "changes the constant value for the duration of the example" do
stub_const("Foo::SIZE", 10)
expect(Foo::SIZE).to eq(10)
end
end
See Myron Marston's announcement for more details:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With