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:
parent
26a35978f6
commit
fdde3a50a4
|
@ -905,6 +905,10 @@ module Shoulda
|
||||||
self
|
self
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def join_table(join_table_name)
|
||||||
|
self
|
||||||
|
end
|
||||||
|
|
||||||
def description
|
def description
|
||||||
description = "#{macro_description} #{name}"
|
description = "#{macro_description} #{name}"
|
||||||
description += " class_name => #{options[:class_name]}" if options.key?(:class_name)
|
description += " class_name => #{options[:class_name]}" if options.key?(:class_name)
|
||||||
|
|
|
@ -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.to fail_with_message_including('missing columns: person_id, relative_id')
|
||||||
end
|
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
|
context 'using a custom foreign key' do
|
||||||
it 'rejects an association with a join table with incorrect columns' do
|
it 'rejects an association with a join table with incorrect columns' do
|
||||||
define_model :relative
|
define_model :relative
|
||||||
|
|
Loading…
Reference in New Issue