Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 52 lines (44 sloc) 2.106 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
require "spec_helper"

describe CanCan::ActiveRecordAdditions do
  before(:each) do
    @model_class = Class.new(Person)
    stub(@model_class).scoped { :scoped_stub }
    @model_class.send(:include, CanCan::ActiveRecordAdditions)
    @ability = Object.new
    @ability.extend(CanCan::Ability)
  end

  it "should call where('true=false') when no ability is defined so no records are found" do
    stub(@model_class).where('true=false').stub!.joins(nil) { :no_match }
    @model_class.accessible_by(@ability, :read).should == :no_match
  end

  it "should call where with matching ability conditions" do
    @ability.can :read, @model_class, :foo => {:bar => 1}
    stub(@model_class).where(:foos => { :bar => 1 }).stub!.joins([:foo]) { :found_records }
    @model_class.accessible_by(@ability, :read).should == :found_records
  end

  it "should default to :read ability and use scoped when where isn't available" do
    @ability.can :read, @model_class, :foo => {:bar => 1}
    stub(@model_class).scoped(:conditions => {:foos => {:bar => 1}}, :joins => [:foo]) { :found_records }
    @model_class.accessible_by(@ability).should == :found_records
  end

  it "should merge association joins and sanitize conditions" do
    @ability.can :read, @model_class, :foo => {:bar => 1}
    @ability.can :read, @model_class, :too => {:car => 1, :far => {:bar => 1}}

    condition_variants = [
        '(toos.far.bar=1 AND toos.car=1) OR (foos.bar=1)', # faked sql sanitizer is stupid ;-)
        '(toos.car=1 AND toos.far.bar=1) OR (foos.bar=1)'
    ]
    joins_variants = [
        [:foo, {:too => [:far]}],
        [{:too => [:far]}, :foo]
    ]

    condition_variants.each do |condition|
      joins_variants.each do |joins|
        stub(@model_class).scoped( :conditions => condition, :joins => joins ) { :found_records }
      end
    end
    # @ability.conditions(:read, @model_class).should == '(too.car=1 AND too.far.bar=1) OR (foo.bar=1)'
    # @ability.associations_hash(:read, @model_class).should == [{:too => [:far]}, :foo]
    @model_class.accessible_by(@ability).should == :found_records
  end
end
Something went wrong with that request. Please try again.