5

假设我在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
4

1 回答 1

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
于 2008-11-11T12:19:55.343 回答