期待<" index">但使用< []>进行渲染

时间:2014-07-09 12:20:06

标签: ruby-on-rails rspec

gemfile:

source 'https://rubygems.org'
gem 'rails', '4.1.1'
gem 'mysql2'
gem 'sass-rails', '~> 4.0.3'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0',          group: :doc
gem 'tzinfo-data', platforms: [:mingw, :mswin]
gem 'devise'
gem 'cancan'
gem 'attr_encrypted'
gem 'faker', '1.0.1'
gem 'jdbc-mysql', '5.1.28', :platform => :jruby
gem 'thinking-sphinx', '~> 3.1.0'
gem 'kaminari'
gem 'postmark-rails', '~> 0.5.0' 
gem 'slim-rails'
gem 'strong_password', '~> 0.0.3'
gem 'jquery-turbolinks'
gem 'whenever', :require => false 
gem 'nokogiri'
gem 'mechanize'
gem 'prawn'
gem 'render_csv', '~> 2.0.0'
gem 'capistrano', '~> 3.2.0'

group :development, :test do
  gem "capybara", "2.2.1"
  gem "cucumber-rails",     "~> 1.3.0", require: false 
  gem 'rspec-rails', '~> 3.0.0'
  gem "factory_girl_rails", "~> 4.1.0"
end

gem 'hirb', group: :development

spec / spec_helper.rb

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment",__FILE__)
require 'rspec/rails'
require "capybara/rspec"
include Capybara::DSL

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
  config.extend ControllerMacros, :type => :controller
end

规格/支持/ controller_macros.rb

module ControllerMacros
  def login_admin
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:admin]
      sign_in FactoryGirl.create(:admin) # Using factory girl as an example
    end
  end
end

规格/工厂/ factory.rb

FactoryGirl.define do
  factory :user do
    email "test@test.com"
    password "12345678"
  end
end

categories_controller.rb

class CategoriesController < ApplicationController
  before_filter :authenticate_user!, :load_key!

  def index
    @categories = Category.where("user_id is null or user_id = ?", current_user).order(updated_at: :desc)
  end
  private

  def category_params
    params.require(:category).permit(:title)
  end
end

规格/控制器/ categories_controller_spec.rb

require 'rails_helper'

describe CategoriesController do
    login_user

    it "redirect when something went wrong" do
      get :index
      expect(response).to render_template("index")
    end
end

给我:

1)当出现问题时,CategoriesController重定向
    失败/错误:期望(响应).to render_template(“index”)
      期待&lt;“index”&gt;但使用&lt; []&gt;

进行渲染

1 个答案:

答案 0 :(得分:6)

首先,检查一下,如果您的操作按预期工作,请添加一些输出作为最后一行并查看是否已打印。然后,如果要像这样测试模板渲染,则应使用render_views

require 'rails_helper'

describe CategoriesController do
  render_views
  login_user

  it "redirect when something went wrong" do
    get :index
    expect(response).to render_template("index")
  end
end