开发者

Rails Beginner Testing Question for RSpec with CanCan

开发者 https://www.devze.com 2023-03-31 08:15 出处:网络
I am currently using cancan with rspec. Please take a look at my ability.rb require \'spec_helper\' require \"cancan/matchers\"

I am currently using cancan with rspec.

Please take a look at my ability.rb

require 'spec_helper'
require "cancan/matchers"

class Ability

  include CanCan::Ability

  def initialize(user)
    if user       # Only logged in users
      if user.role? :admin
        can :manage, :all

      elsif user.role? :producer
        can :read, Business
        can :update, Business do |b|
          b.user_id == user.id
        end
        can :redeem, Purchase 

      elsif user.role? :consumer
        can :your, Deal
        can [:create, :redirect_to_wepay], Purchase
        can :show, Purchase do |purchase|
          purchase.user_id == user.id
        end
      end

      # Good thing about devise with Cancan is that it takes care of this.
      can :manage, User do |the_user|
        the_user.id == user.id
      end

    else
      # This is needed for the cans that follows
      user = User.new

    end

    # Everyone's session
    can :read, Deal
    can :read, Business

    # You have to enable it for wepay
    can [:sold_out, :callback, :received], Purchase开发者_如何学编程

  end
end

In my spec/models/ability_spec.rb I have

describe Ability do 

  describe "consumers" do
    describe "cancan" do 
      before(:each) do
        @user = Factory(:user, :role => "consumer")
        @ability = Ability.new(@user)
      end

      describe "success" do 
        #**This line I am getting ability is nil
        @ability.should == 5

        #**This line gives me be_able_to undefined
        #@ability.should_not be_able_to(:read, Factory(:deal))

        #@ability.can(:read, Factory(:business)).should be_true
      end

Any ideas why I am getting @ability as nil?

In addition, I want to put some of my controller's actions that are related to permission control in this ability_spec.rb file. Is that possible? (I explicitly want to achieve this because my app has 3 roles of users and I find myself littering my controllers spec files with all these permission related one liners.

Thanks!


Tests must appear in it or specify blocks. describe and context are simply for grouping.

describe "success" do 
  #**This line I am getting ability is nil
  @ability.should == 5
end

Should be more like:

it "allows consumers to do blah blah blah" do 
  @ability.should == 5
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号