簡體   English   中英

RSpec控制器規范中的CanCan

[英]CanCan in RSpec Controller spec

我一整天的時間都在嘗試解決控制器規格方面的問題,而當前的解決方法對我來說似乎是不可接受的。 為什么這樣做有效? ...以及我應該怎么做。

給定一個簡單的層次結構,如下所示,並具有下面的capability.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

Ability.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

啊! 我自己找到的。

這里是:

config.include Devise::TestHelpers, :type => :controller

以下是在Devise文檔的指導下登錄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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM