Permalink
Browse files

add tests for merging conditions and joins

  • Loading branch information...
1 parent 9c0346b commit ac19422a901a5681b31688b2fe5b959b3e3cc2b5 Yura Sokolov committed May 25, 2010
Showing with 37 additions and 2 deletions.
  1. +24 −1 spec/cancan/active_record_additions_spec.rb
  2. +13 −1 spec/spec_helper.rb
@@ -2,7 +2,7 @@
describe CanCan::ActiveRecordAdditions do
before(:each) do
- @model_class = Class.new
+ @model_class = Class.new(SqlSanitizer)
stub(@model_class).scoped { :scoped_stub }
@model_class.send(:include, CanCan::ActiveRecordAdditions)
@ability = Object.new
@@ -25,4 +25,27 @@
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.sql_conditions(:read, @model_class).should == '(too.car=1 AND too.far.bar=1) OR (foo.bar=1)'
+ @ability.association_joins(:read, @model_class).should == [{:too => [:far]}, :foo]
+ @model_class.accessible_by(@ability).should == :found_records
+ end
end
View
@@ -25,10 +25,22 @@ class Person
class SqlSanitizer
def self.sanitize_sql(hash_cond)
case hash_cond
- when Hash then hash_cond.map{|name, value| "#{name}=#{value}"}.join(' AND ')
+ when Hash
+ sanitize_hash(hash_cond).join(' AND ')
when Array
hash_cond.shift.gsub('?'){"#{hash_cond.shift.inspect}"}
when String then hash_cond
end
end
+
+ private
+ def self.sanitize_hash(hash)
+ hash.map do |name, value|
+ if Hash === value
+ sanitize_hash(value).map{|cond| "#{name}.#{cond}"}
+ else
+ "#{name}=#{value}"
+ end
+ end.flatten
+ end
end

0 comments on commit ac19422

Please sign in to comment.