Explicitly test custom `:join_table` option #547

Some developers might want to pass a :join_table option to their HABTM
association declarations (e.g., `has_and_belongs_to_many :posts,
join_table: :users_and_their_posts). Those same developers, may want to
explicitly test the existence of the join table. Make this possible.
This commit is contained in:
Jacob Morris 2014-07-23 17:26:15 -06:00 committed by Elliot Winkler
parent 26a35978f6
commit fdde3a50a4
2 changed files with 46 additions and 0 deletions

View File

@ -905,6 +905,10 @@ module Shoulda
self
end
def join_table(join_table_name)
self
end
def description
description = "#{macro_description} #{name}"
description += " class_name => #{options[:class_name]}" if options.key?(:class_name)

View File

@ -886,6 +886,48 @@ describe Shoulda::Matchers::ActiveRecord::AssociationMatcher, type: :model do
end.to fail_with_message_including('missing columns: person_id, relative_id')
end
it "rejects an association with a bad :join_table option" do
define_model :relative
join_table_name = 'people_and_their_families'
define_model :person do
has_and_belongs_to_many(
:relatives, join_table: join_table_name
)
end
create_table("people_relatives", id: false) do |t|
t.references :person
t.references :relative
end
expect do
expect(Person.new).to(
have_and_belong_to_many(:relatives).join_table(join_table_name)
)
end.to fail_with_message_including("#{join_table_name} doesn't exist")
end
it "accepts an association with a valid :join_table option" do
define_model :relative
join_table_name = 'people_and_their_families'
define_model :person do
has_and_belongs_to_many(
:relatives, join_table: join_table_name
)
end
create_table(join_table_name, id: false) do |t|
t.references :person
t.references :relative
end
expect(Person.new).to(
have_and_belong_to_many(:relatives).join_table(join_table_name)
)
end
context 'using a custom foreign key' do
it 'rejects an association with a join table with incorrect columns' do
define_model :relative