2013-02-12 74 views
0

我花了大部分時間試圖根據控制器規範解決問題,目前的解決方法對我來說似乎是不可接受的。任何承擔爲什麼這個作品? ...而我應該做的。RSpec控制器中的CanCan規範

給出一個簡單的層次結構,如下,下面ability.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 
+0

您是否配置了rspec來使用devise helpers? config.include Devise :: TestHelpers,:type =>:controlle – Novae 2013-02-12 23:05:51

+0

你有沒有登錄過測試用戶?否則這個能力會使用一個新的用戶對象...(你可以使用上面評論中提到的幫助者登錄用戶。) – manoj 2013-02-13 05:08:54

+0

我確實配置了Devise :: TestHelpers。我的路線如下: – 2013-02-21 16:16:03

回答

0

精氨酸!自己找到了。

這就是:

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