Skip to content

Instantly share code, notes, and snippets.

@jc00ke
Created May 9, 2011 23:37
Show Gist options
  • Save jc00ke/963647 to your computer and use it in GitHub Desktop.
Save jc00ke/963647 to your computer and use it in GitHub Desktop.
Stubbing controller_name & action_name in Rails 3 with rspec 2.5
module ApplicationHelper
def foo
controller_name == 'widgets' && action_name == 'index'
end
end
require 'spec_helper'
describe ApplicationHelper do
describe '#foo' do
context "on Widgets#index" do
it "returns true" do
controller.stub(:controller_name).and_return('widgets')
controller.stub(:action_name).and_return('index')
helper.foo.should be_true
end
end
context "not on Widgets#index" do
it "returns false" do
controller.stub(:controller_name).and_return('widgets')
controller.stub(:action_name).and_return('show')
helper.foo.should be_false
end
end
end
end
@jc00ke
Copy link
Author

jc00ke commented Apr 4, 2012

@redconfetti glad it helped! I refactored it a little to use contexts, but otherwise, yeah, that's the way 😄

@gcaixeta
Copy link

thanks :)

@spalenza
Copy link

spalenza commented Mar 2, 2015

Is it still working? (rspec 3.2.0)
I had success this way:

before { allow(self).to receive(:controller).and_return(HelloController) }

@darrenterhune
Copy link

darrenterhune commented Jan 21, 2017

https://relishapp.com/rspec/rspec-mocks/v/3-5/docs

allow(die).to receive(:roll) { 3 }

So...

allow(self).to receive(:controller_name) { Widgets }
allow(self).to receive(:action_name) { 'show' }

@wickkidd
Copy link

I was beating my head against the wall trying to reasonably mock controller based on

module MyHelper
  def render_some_partial?
    controller.is_a?(SomeNamespace::WidgetController)
  end
end

when your idea was so much easier (I needed to ensure namespace)

module MyHelper
  def render_some_partial?
    controller_path == 'some_namespace/widgets'
  end
end

I think this stems from thinking more in the base language than the framework as I've gained more experience (ruby vs rails, js vs react/vue/etc...).

Anyway, thanks from 2018 Jesse. :)

@jsugarman
Copy link

Worked for me when above did not - a rails 6, rspec 3.9 - in spec/helpers/my_helper_spec.rb

before do
  allow(controller).to receive(:controller_name).and_return 'Widgets'
  allow(controller).to receive(:action_name).and_return 'show'
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment