【问题标题】:rspec undefined method `mobile_device?' for #<#<Classrspec未定义方法`mobile_device?对于#<#<类
【发布时间】:2014-11-22 00:01:32
【问题描述】:

如果正在移动设备上查看应用程序并且我从 rake 收到此错误(但它在 localhost 上完美运行),我正在尝试向我的标题模板的一部分添加一个新类:

失败/错误:渲染:模板 => "/layouts/_header.html.erb" 动作视图::模板::错误: 未定义的方法“mobile_device?”对于#

这是导致我的标题模板中出现问题的行:

./app/views/layouts/_header.html.erb

<div class="<%= 'flexslider-mobile' if mobile_device? && !current_page?('/') %>">
  <some html>
</div>

这是我在测试中渲染模板时遇到的问题:

./spec/views/layouts/application_spec

require 'spec_helper'

describe 'header' do

  before(:each) do
    render :template => "/layouts/_header.html.erb"
  end

./app/controllers/application_controller.rb

class ApplicationController < ActionController::Base

   protected

def mobile_device?
    if session[:mobile_param]
      session[:mobile_param] == "1"
    else
      request.user_agent =~ /Mobile|webOS/
    end
  end
  helper_method :mobile_device?
end

我是 rails 和 rspec 的新手,所以我确信这很明显,我只是不知道...感谢您的帮助!

【问题讨论】:

  • 你试过mobile_device方法了吗?退出受保护的?
  • 尝试将其移出受保护的状态,但这并没有什么不同。不确定“方法 mobile_device”是什么意思?你可以解释吗?谢谢
  • 我的意思是移动 mobile_device?脱离保护..就是这样
  • 啊,真可惜。是的,似乎没关系。

标签: ruby-on-rails methods rspec


【解决方案1】:

helper_method 调用必须在 protected 关键字之上声明。

【讨论】:

  • 我已经尝试过了,但遗憾的是仍然失败了。
【解决方案2】:

原来视图测试没有控制器上下文,所以我需要在渲染之前存根方法:

  before(:each) do
    view.stub("mobile_device?" => false)
    render :template => "/layouts/_header.html.erb"   
  end

效果很好。感谢 danpickett 在 stackoverflow 之外提供的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多