ruby-on-rails - 如何在测试期间在 Helper 中 stub 函数

标签 ruby-on-rails ruby-on-rails-3

看看这个辅助函数:

def show_welcome_banner?
  (controller_name == 'competition' && action_name == 'index') ||
  (controller_name == 'submissions' && action_name == 'show')
end

它期望定义 controller_name 和 action_name 函数。

我试图在我的 RSpec 匹配器中使用它:

describe PageHelper do
  it "should know when the welcome banner is to be shown" do
    helper.stub!(:controller_name).and_return('index')
    show_welcome_banner?.should == false
  end
end

但这实际上行不通。

我怎样才能在帮助程序中 stub 函数?也许使用 instance_eval? 谢谢!

编辑, 尝试使用

controller.stub!(:controller_name).and_return('index')

但是得到了

  1) PageHelper should know when the welcome banner is to be shown
     Failure/Error: show_welcome_banner?.should == false
     NameError:
       undefined local variable or method `controller_name' for #<RSpec::Core::ExampleGroup::Nested_1:0x1059a10b8>
     # ./app/helpers/page_helper.rb:16:in `show_welcome_banner?'
     # ./spec/helpers/page_helper_spec.rb:7

助手放在spec/helper/page_helper_spec.rb..

最佳答案

你试过吗

stub!(:controller_name).and_return('index')

似乎对我有用:)

关于ruby-on-rails - 如何在测试期间在 Helper 中 stub 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5927132/

相关文章:

ruby-on-rails - 是否可以在 Rails 6 中禁用 Sass?

ruby-on-rails - 多种请求格式的单一 View 模板

ruby-on-rails-3 - 使用 Poltergeist PhantomJS Capybara 驱动程序设置 Cookie

ruby-on-rails - 在 Cygwin 上使用 RVM 安装 Ruby 时遇到问题

ruby-on-rails - 使用 Sidekiq 和 redis 的 Heroku 调度程序

ruby-on-rails - 遍历目录并从 ruby​​ on rails 中的文件读取

ruby-on-rails - Delayed_Job : accessing job metadata and/or avoiding duplicate jobs

ruby-on-rails - Devise Rails 3.1.3 没有路线匹配 [DELETE] "/users/sign_out"

ruby - 从相同方法的 lib 文件中访问 Rails 模型名称

ruby-on-rails - 在 Rails 测试环境中无法使用 TimescaleDB