HABTM creating duplicate records in test environment


#1

I have the following HABTM associations between two models,
MemberEntityAccessibility and MemberEntity:

has_and_belongs_to_many   :member_entities,
                          :class_name => "MemberEntity",
                          :join_table =>

“accessibilities_member_entities”,
:foreign_key => “accessibility_id”,
:association_foreign_key =>
“member_entity_id”

has_and_belongs_to_many :member_entity_accessibilities,
                        :class_name => "Accessibility",
                        :join_table =>

“accessibilities_member_entities”,
:foreign_key => “member_entity_id”,
:association_foreign_key =>
“accessibility_id”

Also in the MemberEntityAccessibility model I have the following code
to allow a member (entity) to be added into the HABTM join table.

def add_member_entity?(entity)
    return false if entity.nil? || member_entities.include?

(entity)
member_entities << entity
true
end

When I am testing my code in the test environment (fixtures etc), my
exhaustive(!) logging reveals that ActiveRecord attempts to insert the
same ‘entity’ record twice into the join table when there is only one
member (entity) object in the collection (member_entities). For
example, where an entity object (id=1) is added to ‘member_entities’
of accessibility object (id=1), ActiveRecord saves two records, each
with a compound key of 1,1.

My logging confirms that the member_entities collection only has one
entry (as expected) and not two.

Any ideas would be much appreciated - I have hit a wall with this one
and wonder if it is something to do with the test environment.


#2

The same code runs fine in the development environment - that is, only
one record is created in the join table.

Am I overlooking a subtlety in the use of the test environment? For
example, I have not defined any fixtures for the join table.


#3

I should add that my test file looks like this:

require ‘test_helper’

class MemberEntityTest < ActiveSupport::TestCase

fixtures :users, :member_entities, :properties

def setup

@administrator = member_entities(:administrator)
@bob = member_entities(:bob)

end

test “create a group” do

Group.create({:owner => @bob, :pingee_name => "London Albion

Players"})

#does Bob own the new group?
assert_equal @bob, new_group.owner

end
end

The ‘create’ method in the Group model (which inherits from
MemberEntity) create the join table records as well as a bunch of
other stuff.

Thank you.