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

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
有帮助吗?

解决方案

您可以将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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top