Stubbing and extending a class "rspec style"

42 views Asked by At

In a Rspec test, I'm creating and extending the "Queryable" class:

  let(:queryable) do
    class Queryable
     include FeatureQuery
    end.new
 end

that class doesn't exist in the app, but the FeatureQuery modules does. This code works well, but it feels ugly and hacky: is there a way to do it using a rspec double?

2

There are 2 answers

2
Tom Lord On

I'm not sure if this counts as "less ugly and hacky", but you can create an anonymous class to bypass giving this test class a name:

let(:queryable) do
  Class.new.include(FeatureQuery).new
end

A couple of other options you could consider are:

  1. Write the tests against a real class in your application that includes FeatureQuery.
  2. Test the FeatureQuery module directly, rather than some class it gets included into.
0
Edil Talantbekov On

Maybe it's better to mock this class?

allow_any_instance_of(FeatureQuery).to receive(:foo).and_return(:bar)