psyho / bogus

Fake library for Ruby
Other
359 stars 14 forks source link

Stub an instance of a class as a constant #35

Closed allenwyma closed 10 years ago

allenwyma commented 10 years ago

It seems when you add in bogus, it won't let you call RSpec methods anymore? If that's so, I'm okay with that, but there's one feature that is missing that's rather important with my unit tests.

I have a constant that is an instance of an ActiveMerchant gateway, is there a way I can stub that so I can test?

psyho commented 10 years ago

I think we overlooked that use case.

I think the syntax for "stubbing" constants could look like this:

fake_const(Foo, as: :instance) { ActiveMerchant::Gateway }

and once we implement duplicating an objects interface (fake(as: :object)), the syntax would become even simpler:

fake_const(Foo)

For now, you could use the following snippet to stub constants using our internal API:

def stub_const(name, value)
  previous_value = eval(name)
  Bogus.inject.overwrites_classes.overwrite(name, value)
  Bogus.inject.overwritten_classes.add(name, previous_value)
end

I'll try to get faking constants into the next release. Thanks for reporting!

allenwyma commented 10 years ago

So how do I use this? I'm trying to stub a method on the constant and return a fake response.

psyho commented 10 years ago

I'm closing this issue because the progress on the feature is tracked in #46.