Supercomputer Stub in the controller

How to stub: Super method from included module. I have a controller:

class ImportsController < BaseController
   include ImportBackend

  def import_from_file
    super
  rescue TransferPreview::Error => exc
    flash[:error] = "Some String"
    redirect_to imports_path
  end
end

      

And the importBackend module:

module ImportBackend
  def import_from_file
    //something
  end
end

      

I want to test this controller. My question is, how can I stub a method in ImportBackend to raise the error? I've tried a couple of solutions but nothing seems to work:

ImportBackend.stub(:import_from_file).and_raise(Transfer::Error)
controller.stub(:super).and_raise(Transfer::Error)
controller.stub(:import_from_file).and_raise(Transfer::Error)

      

Thanks for all the answers.

+3


source to share


1 answer


super

looks like a method in Ruby , but it's actually a keyword with special behavior (for example, super

and super()

does different things than any other Ruby method) and you can't stub it.

What you really want to do is stub the method being called super

, which is in this case ImportBackend#import_from_file

. Since this is a mixin from a module (not a superclass), you cannot stub it in the usual way. However, you can define a dummy module you want and include

it's in your class. This works because when multiple modules define a mixin, it super

will refer to the last one included. You can read more about this approach here . In your case, it will look something like this:



mock_module = Module.new do
  def import_from_file
    raise Transfer::Error
  end
end

controller.singleton_class.send(:include, mock_module)

      

Depending on your other specs, this might lead to some complications when breaking, but I hope this helps you get started.

+6


source







All Articles