2008-11-11 20 views
5

“控制器”比方说,我有下面的代码在application_helper.rb撷取“ACTION_NAME”或帮手规范

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

这将做一些事情,如果所谓的指数操作中。

问:如何重写application_helper_spec.rb中的帮助程序规范以模拟来自'index'操作的调用?

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 

回答

7

您可以存根ACTION_NAME方法你想要的任何值:

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 
+0

存根! (:index_name).and_return('index'),not helper.stub!(:action_name).and_return('index') 感谢rsim :)在帮助器中,该死的错过了尝试, – edthix 2008-11-11 12:40:46