【问题标题】:Fetching 'action_name' or 'controller' from helper spec从帮助规范中获取“action_name”或“控制器”
【发布时间】:2008-11-11 10:38:34
【问题描述】:

假设我在 application_helper.rb 中有以下代码:

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

如果在索引操作中调用它会做一些事情。

问:如何在 application_helper_spec.rb 中为此重写帮助规范以模拟来自“索引”操作的调用?

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

【问题讨论】:

    标签: ruby-on-rails ruby rspec bdd


    【解决方案1】:

    您可以将 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
    

    【讨论】:

    • 存根!在助手处,该死的错过了尝试,我做了存根!(:action_name).and_return('index'),而不是helper.stub!(:action_name).and_return('index')谢谢rsim :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 2011-11-07
    • 2015-01-23
    • 2010-11-08
    • 1970-01-01
    相关资源
    最近更新 更多