ruby-on-rails - 从助手规范中获取 'action_name' 或 'controller'

标签 ruby-on-rails ruby rspec bdd

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

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

如果在 index 操作中调用,它将执行某些操作。

问:如何在 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

最佳答案

您可以将 action_name 方法 stub 为您想要的任何值:

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

关于ruby-on-rails - 从助手规范中获取 'action_name' 或 'controller',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/280548/

相关文章:

ruby-on-rails - (Rails 4.2) 如何从 View 触发脚手架生成?

ruby-on-rails - Rails - 通过参数传递多个复选框值

javascript - 查找具有特定键值对的 JS 对象/哈希

ruby-on-rails - rspec spec 自动逻辑分组(按 "tags")

ruby-on-rails - 为什么自动测试有时会在失败后立即重新运行所有规范?

ruby-on-rails - Rails 路由重定向到内部 url

ruby-on-rails - 按日期(或任何其他列)对 ActiveRecord 返回的数组进行排序

ruby - 在 Ruby 中使用 TomDoc,表示 splat 参数的正确方法是什么?

ruby - stub include_recipe 调用以不采取任何操作,但仍将配方计为包含的内容

ruby-on-rails - RSpec中的灯具