Saturday, February 19, 2011

Fetching 'action_name' or 'controller' from helper spec

Hi all, my first question here.

Let say 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 within index action

Q: How do I rewrite the helper spec for this in application_helper_spec.rb to meet simulate a call from '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
From stackoverflow
  • You can stub action_name method to whatever 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
    
    Ed : stub! at helper, damn missed trying that out, I did stub!(:action_name).and_return('index'), not helper.stub!(:action_name).and_return('index') Thanks rsim :)

0 comments:

Post a Comment