Retrieving "action_name" or "controller" from the helper specification

Say that I have the following code in application_helper.rb :

def do_something
 if action_name == 'index'
   'do'
 else
   'dont'
 end
end

which will do something if called in index action.

Q: How to rewrite the supporting specification for this in application_helper_spec.rb to simulate a call from the "index" action?

describe 'when called from "index" action' do
  it 'should do' do
    helper.do_something.should == 'do' # will always return 'dont'
  end
end

describe 'when called from "other" action' do
  it 'should do' do
    helper.do_something.should == 'dont'
  end
end
+5
source share
1 answer

You can stub the action_name method with any value you want:

describe 'when called from "index" action' do
  before
    helper.stub!(:action_name).and_return('index')
  end
  it 'should do' do
    helper.do_something.should == 'do'
  end
end

describe 'when called from "other" action' do
  before
    helper.stub!(:action_name).and_return('other')
  end
  it 'should do' do
    helper.do_something.should == 'dont'
  end
end
+7
source

All Articles