ruby-on-rails - Controller 测试使用 Rspec 显示页面,它给出错误 nil & 并渲染空页面

标签 ruby-on-rails unit-testing rspec tdd

我是 TDD on Rails 的新手,我正在尝试使用“Everyday Rails Testing with Rails”一书来测试 video_controller 以进行简单的显示页面,但它给了我错误“nil”并呈现为空,如下所示。但我真的不知道我做错了什么。请建议我。感谢您的帮助。

规范/ Controller /videos_controller_spec.rb

require 'spec_helper'

describe VideosController do
  describe "GET show" do
   before {@video1 = Video.create!(title: 'Family Guy', description: 'Some description')}

     it "assigns the requested video to the @video" do
      get :show, id: @video1
      assigns(:video).should == @video1
    end

    it "render show tempalte" do
      get :show, id: @video1
      response.should render_template :show
    end
  end
end

应用程序/ Controller /videos_controller.rb

class VideosController < ApplicationController
  before_filter :require_user  

  def show 
    @video = Video.find(params[:id])
  end
end

我的终端出现错误:

Failures:

  1) VideosController GET show assigns the requested video to the @video
     Failure/Error: assigns(:video).should == @video1
   expected: #<Video id: 1, title: "Family Guy", small_cover_url: nil, large_cover_url: nil, description: "Some description", created_at: "2013-05-13 00:12:32", updated_at: "2013-05-13 00:12:32">
        got: nil (using ==)
 # ./spec/controllers/videos_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

  2) VideosController GET show render show tempalte
     Failure/Error: response.should render_template :show
   expecting <"show"> but rendering with <"">
 # ./spec/controllers/videos_controller_spec.rb:14:in `block (3 levels) in <top (required)>

最佳答案

Controller 中有一个before_filter

before_filter :require_user

您尚未在测试中提供所需的操作,因此尚未达到真正的操作 show

要修复此问题,只需在 get :show 之前添加必要的操作(例如创建用户或登录)

关于ruby-on-rails - Controller 测试使用 Rspec 显示页面,它给出错误 nil & 并渲染空页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16513366/

相关文章:

ruby-on-rails - 如何指定私有(private)方法

rspec - Rspec模型关联

ruby-on-rails - heroku db :push not working, 使用 taps gem

ruby-on-rails - 自定义 rails_admin Controller 操作的 Rspec 测试?

java - 当一个函数调用另一个返回 boolean 值的函数时如何进行单元测试?

unit-testing - 具有自定义 ServeHTTP 实现的 http 处理程序的 golang 单元测试

java - 仅验证少数元素的单元测试

ruby-on-rails - 将 Timecop gem 用于范围

ruby-on-rails - 有没有一种轻量级的方法来锁定哈希上的一组 key ?

javascript - 如何在 Rails 中实现字计数器?