ruby-on-rails - Rails 中的 stub 模型方法

标签 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

这是 Controller 。

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 should select the index template for rendering Failure/Error: get :index, { :q => "KgfdlZuVz7I" } received :video_exists? with une xpected arguments expected: ("KgfdlZuVz7I") got: (no args) Please stub a default value first if message might be received with other args as well. # ./app/controllers/videos_controller.rb:5:in index' # ./spec/controllers/videos_controller_spec.rb:12:inblock (3 levels) in '

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

最佳答案

作为建议 #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

关于ruby-on-rails - Rails 中的 stub 模型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12481121/

相关文章:

ruby-on-rails - bundle 安装通过没有错误,但在访问该站点时,我看到一个错误

css - 文件的 Rails-Heroku-SASS 语法错误

ruby-on-rails - 带有 check_box 渲染列表的 Form_for

ruby - 没有 key 的散列在 Ruby 中意味着什么?

ruby - 如何检查数组数组中是否存在键?

ruby-on-rails - rake 分贝 :test:prepare in Rails 3 app fails with file not found

ruby-on-rails - less-rails-bootstrap ... 哪里有 less 文件

ruby - 确定使用Ruby MP4Info gem之类的Apple AAC与无损格式?

ruby-on-rails - Stubing 费加罗与 rspec

ruby-on-rails - Ruby on Rails 3 + Rspec + capybara : check response status