-2

I am using Ruby on Rails with some hardware which is not available on my development machine.

Using Rails.env I want to "double" an instance of a class so that the "real implementation" isn't called (~double class XY iff Rails.env == :production).

I have tried rspec-mocks's double, but it needs expectations and throws exceptions otherwise.

phikes
  • 565
  • 5
  • 13

1 Answers1

0

In the end I used the following code:

class Double
    def method_missing(m, *args, &block)
        puts "#{m} was called with arguments: #{args.join(', ')}"
    end
end

Of course this does not work for methods which are declared on Object, but it was sufficient for my needs. Also it does not give the ability to pass in parameters.

Furthermore I wrote a little helper function to instantiate objects based on class constants. Since there were some singletons in my code I also implemented a check for that. This way the real classes are only instantiated when the rails environment is 'production'.

def instance_of(c)
    if Rails.env == 'production'
        if c.ancestors.include? Singleton
            c.instance
        else
            c.new
        end
    else
        Double.new
    end
end

Example usage: SOME_CONST = instance_of ModuleXY::ClassZ.

phikes
  • 565
  • 5
  • 13