Reputation: 1092
I'm creating a gem that will have a constant in whatever app it is being used in (after a generator is run), but that constant doesn't exist in the gem itself. I'm having an issue with RSpec inside the gem not skipping over the part of code that is calling the constant. A simple example of what is going on is below.
class Foo
def self.do_something
Bar.send(FakeConstant.name) #Bar.send is a valid class and method
end
end
foo_spec.rb
it 'does something'
expect(Bar).to receive(send).and_return('skipped!')
Foo.do_something
end
rspec output
NameError: uninitialized constant FakeConstant
I want to write the test so that it skips over the Bar.send
call completely so that it never knows that there is a bad constant inside of it. There really isn't a good way to get around this.
Upvotes: 1
Views: 2386
Reputation: 37627
RSpec's stub_const
method allows you to stub a constant:
it 'does something'
stub_const(FakeConstant, double(name: "Fakey McFakerson"))
expect(Bar).to receive(send).and_return('skipped!')
Foo.do_something
end
More here: https://www.relishapp.com/rspec/rspec-mocks/docs/mutating-constants/stub-defined-constant
That said, I agree with BroiSatse that it would be probably be nicer to provide a more dynamic means of getting that information into your code that could be manipulated in tests with less trickery.
Upvotes: 3