【问题标题】:CanCan in RSpec Controller specRSpec 控制器规范中的 CanCan
【发布时间】:2023-07-30 11:27:02
【问题描述】:

我花了一天的大部分时间试图根除控制器规范的问题,而当前的解决方法对我来说似乎是不可接受的。任何关于为什么这有效? ...以及我应该做什么。

给定一个简单的层次结构如下,以及下面的能力.rb,properties_controller_spec.rb 不允许下面的规范在没有以下行的情况下通过:

ability = Ability.new(subject.current_user)

你能告诉我为什么会这样吗?

谢谢!

型号:

class Account < ActiveRecord::Base
  has_many :properties, :dependent => :nullify
end

class Property < ActiveRecord::Base
  belongs_to :account
end

class User < Refinery::Core::BaseModel #for RefineryCMS integration
  belongs_to :account
end

能力.rb:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new
    if user.has_role? :user
      can [:read, :create, :update, :destroy], Property, account_id: user.account_id
    else
      can [:show], Property
    end
  end
end

properties_contoller_spec.rb:

require 'spec_helper'

describe PropertiesController do
  def valid_attributes
  describe "Authenticated as Property user" do
    describe "PUT update" do
      describe "with invalid params" do
        it "re-renders the 'edit' template" do
          property = FactoryGirl.create(:property, account: property_user.account)
          # Trigger the behavior that occurs when invalid params are submitted
          Property.any_instance.stub(:save).and_return(false)
          ability = Ability.new(subject.current_user) # seriously?
          put :update, {:id => property.to_param, :property => {  }}, {}
          response.should render_template("edit")
        end
      end
    end
  end
end

【问题讨论】:

  • 您是否已将 rspec 配置为使用设计助手? config.include Devise::TestHelpers, :type => :controlle
  • 您是否在测试中登录过任何用户?否则该功能将使用新的用户对象...(您可以使用上述评论中提到的帮助器登录用户。)
  • 我确实配置了 Devise::TestHelpers。我的线路如下:
  • Arg!这里是: config.include Devise::TestHelpers, :type => :controller 以下是按照设计文档的指示登录 property_user 的代码。 (有问题的本地人是在包含的 global_variables.rb 中创建的。这些在所有地方都使用。) def signed_in_as_a_property_user property_user.add_role "User" sign_in property_user end def sign_in_as_a_property_user property_user.add_role 'User' post_via_redirect user_session_path, 'user[ email]' => property_user.email, 'user[password]' => property_user.password end

标签: ruby-on-rails rspec devise cancan


【解决方案1】:

啊!自己找的。​​p>

这里是:

config.include Devise::TestHelpers, :type =&gt; :controller

以下是按照设计文档的指示登录 property_user 的代码。 (有问题的本地人是在包含的 global_variables.rb 中创建的。这些在所有地方都使用。)

def signed_in_as_a_property_user
  property_user.add_role "User" 
  sign_in property_user 
end

def sign_in_as_a_property_user 
  property_user.add_role 'User' 
  post_via_redirect user_session_path, 
    'user[email]' => property_user.email,
    'user[password]' => property_user.password
end

【讨论】: