【问题标题】:Stubbing model method in RailsRails 中的存根模型方法
【发布时间】:2012-09-18 16:24:40
【问题描述】:

我正在为 cotroller 编写测试,但没有成功。我的测试是:

describe VideosController do
  describe 'index' do
    it 'should select the index template for rendering' do
      Video.stub(:video_exists?).with("KgfdlZuVz7I").and_return(true)
      get :index, { :q => "KgfdlZuVz7I" }
      response.should render_template('index')
    end
  end
end

这里是控制器。

class VideosController < ApplicationController
  def index
    if params[:q]
      params_hash = CGI::parse(params[:q])
      if Video.video_exists?(params_hash.values[0][0])
        video = Video.new :video_id => params_hash.values[0][0]
        if video.save!
          flash[:notification] = "Video found."
        else
          flash[:notification] = "Video found but not saved to database."
        end
        redirect_to root_path  
      else
        flash[:notification] = "Video not found."
        redirect_to root_path
      end
    end
  end
end

测试未通过并引发消息:

VideosController 索引应该选择索引模板进行渲染 失败/错误:获取 :index, { :q => "KgfdlZuVz7I" } 收到:video_exists?与 预期参数 预期:(“KgfdlZuVz7I”) 得到:(无参数) 如果消息也可能与其他参数一起接收,请先存根默认值。 # ./app/controllers/videos_controller.rb:5:in index' # ./spec/controllers/videos_controller_spec.rb:12:inblock (3 个级别) in '

认为我没有以正确的方式存根视频,因为我只存根了 video_exists?但不是新的和保存。但我不知道如何解决这个问题,因为我是 TDD 和 Rspec 的新手。

【问题讨论】:

    标签: ruby-on-rails ruby rspec tdd


    【解决方案1】:

    作为建议#1,您不应该像在测试中那样写出两次“随机字符串”。这极易出现输入错误并且很难目视验证。改用这个:

    rnd_id = "KgfdlZuVz7I"
    Video.stub(:video_exists?).with(rnd_id).and_return(true)
    get :index, { :q => rnd_id }
    

    另外,我不确定params_hash = CGI::parse(params[:q]) 应该做什么。为什么不像平常一样使用参数?

    class VideosController < ApplicationController
      def index
        if params[:q]
          if Video.video_exists?(params[:q])
            video = Video.new :video_id => params[:q]
            if video.save!
              flash[:notification] = "Video found."
            else
              flash[:notification] = "Video found but not saved to database."
            end
            redirect_to root_path  
          else
            flash[:notification] = "Video not found."
            redirect_to root_path
          end
        end
      end
    end
    

    【讨论】:

    • 第一个建议你是对的。第二个不正确。在 params[:q] 中是 URL,我正在为一个参数解析它。例如youtube.com/watch?v=fslkjfas,我想要那个字符串 fslkjfas。无论如何,您的建议并不能帮助我解决测试问题。
    • 你真的尝试过我的建议吗? Rails 为您解析参数,而您无需执行以下操作:CGI::parse(params[:q])
    • 我试过了,对于 params[:q] 我得到了youtube.com/watch?v=fslkjfas。我不想要这个,而只是 fslkjfas。现在明白了吗?
    • “youtube.com/watch?v=" 来自哪里?您的代码中的任何地方都没有引用此 url。
    • 您的测试断言response.should render_template('index'),但您正在控制器中重定向。改为:response.should redirect_to(root_path)
    猜你喜欢
    • 2010-11-03
    • 1970-01-01
    • 2016-01-21
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    相关资源
    最近更新 更多