Question

I am failing to stub a controller method even after reading dozens of threads and blog posts, so here's my situation:

My controller: app/controllers/my_controller.rb

class MyController < ApplicationController
  before_filter :my_private_method, only:[:new]

  # ...

  private

  # This should be stubbed and not fire
  def my_private_method
    binding.pry
    redirect_to '/failure.html'
  end
end

My spec: spec/controllers/my_spec.rb

describe MyController do
  before :each do   
    controller.stub!(:my_private_method).and_return(true)
  end

  it 'should load' do
    binding.pry
    visit new_my_path
    response.status.should == 200
  end
end

My system:

ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-linux]

Rails 3.2.13

Any help?

Incidentally, I find when I use binding.pry to check controller.object_id in my it 'should load' block, I get a different object_id than when I check self.object_id in my_private_method.

Was it helpful?

Solution 2

The solution is to use a method other than visit in the spec. Apparently, visit is intended for feature specs only. Instead, use get or post etc.

OTHER TIPS

Your "incidental" comment is very much related to what is going on here, I think.

I believe the controller variable in your spec is associated with the implicit MyController.new that was done by RSpec when you passed MyController to describe. That instance of MyController, however, is different than the instance that is created by Rails when you visit new_my_path.

I believe you can use MyController.any_instance.stub to do what you want to do here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top