Skip to content

Commit

Permalink
Testing .grouped_scope does not recreate belongs_to :grouping
Browse files Browse the repository at this point in the history
  • Loading branch information
metaskills committed Sep 19, 2008
1 parent 999f9ad commit e98f66b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
11 changes: 6 additions & 5 deletions lib/grouped_scope/class_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ def grouped_scopes
def grouped_scope(*args)
belongs_to_grouped_scope_grouping
args.each do |association|
ung_assoc = reflect_on_association(association)
unless ung_assoc && ung_assoc.macro == :has_many
raise ArgumentError, "Cannot create a group scope for :#{association} because it is not a has_many association."
existing_assoc = reflect_on_association(association)
unless existing_assoc && existing_assoc.macro == :has_many
raise ArgumentError, "Cannot create a group scope for :#{association} because it is not a has_many " +
"association. Make sure to call grouped_scope after the has_many associations."
end
grouped_scopes[association] = true
group_association_options = {:class_name => ung_assoc.class_name, :foreign_key => ung_assoc.primary_key_name}
group_association_options.merge!(ung_assoc.options)
group_association_options = {:class_name => existing_assoc.class_name, :foreign_key => existing_assoc.primary_key_name}
group_association_options.merge!(existing_assoc.options)
has_many "group_#{association}".to_sym, group_association_options
end
include InstanceMethods
Expand Down
8 changes: 6 additions & 2 deletions test/grouped_scope/class_methods_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,12 @@ def setup
assert Employee.reflect_on_association(:grouping)
end

should 'not create more belongs_to :grouping on additional calls' do
Employee.expects(:has_many).with(:grouping).never
should 'raise an exception when has_many association does not exist' do
assert_raise(ArgumentError) { Employee.class_eval{grouped_scope(:foobars)} }
end

should 'not recreate belongs_to :grouping on additional calls' do
Employee.stubs(:belongs_to).never
Employee.class_eval { has_many(:foobars) ; grouped_scope(:foobars) }
end

Expand Down

0 comments on commit e98f66b

Please sign in to comment.