Rails中的Stubbing模型方法

时间:2012-09-18 16:24:41

标签: ruby-on-rails ruby rspec tdd

我正在为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索引应该选择用于渲染的索引模板        失败/错误:get:index,{:q =&gt; “KgfdlZuVz7I”}           收到:video_exists?与une   预期的论点            预期:(“KgfdlZuVz7I”)                 得到:(没有args)           如果可能与其他args一起收到消息,请先存储默认值。        './app/controllers/videos_controller.rb:5:in index' # ./spec/controllers/videos_controller_spec.rb:12:in阻止(3级)'

认为我不是在正确的方式上存储视频,因为我只是存在视频存在?但不是新的和保存。但我不知道如何解决这个问题,因为我是TDD和Rspec的新成员。

1 个答案:

答案 0 :(得分:3)

作为建议#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
相关问题