【问题标题】:Rspec Failure/Error testing devise and cancanRspec失败/错误测试设计和cancan
【发布时间】:2012-11-28 04:37:58
【问题描述】:

我对使用 Rails 进行测试非常陌生,并且似乎迷失在测试的世界中。我目前正在测试我的仪表板控制器,当我从控制器中删除 load_and_authorize_resource 行时,一切都通过了。我正在使用 cancan 进行授权。

dashboard_controller.rb

def update
@dashboard = Dashboard.find(params[:id])

respond_to do |format|
  if @dashboard.update_attributes(params[:dashboard])
    format.html { redirect_to dashboards_path, notice: 'dashboard was successfully updated.' }
    format.json { head :no_content }
  else
    format.html { render action: "edit" }
    format.json { render json: @dashboard.errors, status: :unprocessable_entity }
  end
end
end

dashboard_controller_spec.rb

require 'spec_helper'

describe DashboardsController do

  login_user
  before :each do 
    @dashboard = create(:dashboard, dashboard_name: "My Own Dashboard", id: 1)
  end

  describe "GET #index" do

    it "should have a current_user" do 
      subject.current_user.should_not be_nil
    end

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

    it "Creates new dashboard" do 
      get :new
      response.should render_template :new
    end

  end

  describe "Get #edit" do 

    it "assigns dashboard to @dashboard" do 
      get :edit, id: @dashboard
      assigns(:dashboard).should == @dashboard
    end

    it "renders the :edit template" do 
      get :edit, id: @dashboard
      response.should render_template :edit
    end

  end


end

我从控制台收到的错误

 1) DashboardsController Get #edit renders the :edit template
 Failure/Error: response.should render_template :edit
   expecting <"edit"> but rendering with <"">
 # ./spec/controllers/dashboard_controller_spec.rb:37:in `block (3 levels) in <top (required)>'

无论如何要绕过这个错误而不删除我的dashboard_controller中的load_and_authorize_resource?

【问题讨论】:

  • 你的控制器中有编辑和索引方法吗?我问是因为你没有在控制器代码中指定这些方法。
  • 是的,我有一个编辑方法,但它是简单的查找参数编辑方法,所以我没有包含它

标签: ruby-on-rails ruby rspec rspec2


【解决方案1】:

当涉及到 Devise 时测试控制器是一件非常棘手的事情。你没有提供你的 login_user 代码,但我猜它并没有涵盖所有的基础。根据official Devise documentation,您需要与守望者、Devise 的实用方法等一起提供帮助。我会在这里重复一遍,但它有点长,您也可以找到源头。最相关的部分是:

如果您使用任何控制器规格,则无法开箱即用 devise 的实用方法。

从 rspec-rails-2.0.0 和 devise-1.1 开始,将 devise 放入的最佳方式 您的规格只是将以下内容添加到 spec_helper...

然后添加他们的示例 controller_macros.rb 并调整一些其他的东西,你应该很高兴。但是,请注意,测试您的控制器规范与测试请求规范不同,并且您可能会在此解决方案无法解决的不同场景中遇到挂起(请参阅我自己的一些痛苦和发现 https://stackoverflow.com/a/13275366/9344)。

【讨论】:

    猜你喜欢
    • 2014-02-11
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    相关资源
    最近更新 更多