Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use rspec mocks to stub out version constants?

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?

like image 236
jes5199 Avatar asked Nov 30 '22 11:11

jes5199


2 Answers

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.

like image 128
Drew Olson Avatar answered Dec 03 '22 00:12

Drew Olson


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:

  • http://myronmars.to/n/dev-blog/2012/06/constant-stubbing-in-rspec-2-11
like image 43
bowsersenior Avatar answered Dec 03 '22 00:12

bowsersenior