Rspec控制器错误:期望<"index">,但使用<"">进行渲染。

9

作为一名新手测试者,我在努力使一些控制器测试通过。

下面的控制器测试抛出了错误:

   expecting <"index"> but rendering with <"">

我在其中一个控制器规范中有以下内容:

  require 'spec_helper'

  describe NasController do

  render_views
  login_user

  describe "GET #nas" do
      it "populates an array of devices" do
        @location = FactoryGirl.create(:location)
        @location.users << @current_user
        @nas = FactoryGirl.create(:nas, location_id: @location.id )      
        get :index
        assigns(:nas).should eq([@nas])
      end

      it "renders the :index view" do
        response.should render_template(:index)
      end
    end

在我的控制器宏中,我有以下代码:
  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      @current_user = FactoryGirl.create(:user)
      @current_user.roles << Role.first
      sign_in @current_user
      User.current_user = @current_user
      @user = @current_user
      @ability = Ability.new(@current_user)
    end
  end

我正在使用devise和cancan,并按照它们的测试指南进行操作。我相信我的用户已经登录并具有查看索引操作的能力。

我该怎么做才能让测试通过?

-- 更新1 --

控制器代码:

class NasController < ApplicationController
   before_filter :authenticate_user!
   load_and_authorize_resource

   respond_to :js

   def index

     if params[:location_id]
       ...
     else
     @nas = Nas.accessible_by(current_ability).page(params[:page]).order(sort_column + ' ' + sort_direction)

     respond_to do |format|
      format.html # show.html.erb
     end    
    end
  end
2个回答

14

我认为如果你改变一下

it "renders the :index view" do
  response.should render_template(:index)
end
it "renders the :index view" do
  get :index
  response.should render_template(:index)
end

它应该能够正常工作。

更新:尝试这个

it "renders the :index view" do
  @location = FactoryGirl.create(:location)
  @location.users << @current_user
  @nas = FactoryGirl.create(:nas, location_id: @location.id ) 
  get :index
  response.should render_template(:index)
end

嘿,還是失敗了。之前試過了 - 也試過重複創建位置。不明白。同樣的測試在另一個控制器中通過。 - simonmorley
你的控制器中是否有什么东西阻止你在naz表为空时打开索引? - Ian Armit
不行,我已经尝试删除设备和cancan过滤器。并将查找替换为@nas = Nas.all以防万一。令人沮丧! - simonmorley
你的控制器中的index方法是否包含任何redirect_to重定向? - Ian Armit
如果您能发布索引操作的控制器代码以及其他相关内容,那将会很有帮助。 - Chris Salzberg
login_user 应该放在 before(:each) 块中。 - zetetic

1

我已经在我的端口修复了这个错误,但不知道我们是否遇到了同样的问题。

在我的设置中,我有一个控制器宏,会循环遍历每个响应格式(html、js、json等),并测试该格式下的规格。像个白痴一样,我实际上没有为某些规格存在一个json响应模板,而且我没有意识到如果找不到模板,这将会抛出一个错误。所以这就是我的问题所在。

尝试在你的规格中指定一个格式,如下所示,并在正确的文件夹中编写一些名为index.html的模拟模板,看看是否会出现相同的错误。

get :index, :format => "html"

谢谢建议。我已经尝试过了,但对我没有用。我将尝试在另一个控制器中使其工作并查看差异。 - simonmorley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接