Skip to content

Instantly share code, notes, and snippets.

@uberllama
Last active August 29, 2015 14:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save uberllama/1d0323438700d4f23bbb to your computer and use it in GitHub Desktop.
Erroneous validation on has_many :through with existing record
# Activate the gem you are reporting the issue against.
gem 'activerecord', '4.1.7'
require 'active_record'
require 'minitest/autorun'
require 'logger'
# Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :conversations do |t|
end
create_table :conversation_users do |t|
t.integer :conversation_id
t.integer :user_id
end
create_table :users do |t|
t.string :name
end
end
class Conversation < ActiveRecord::Base
has_many :conversation_users
has_many :users, through: :conversation_users
end
class ConversationUser < ActiveRecord::Base
belongs_to :conversation
belongs_to :user
end
class User < ActiveRecord::Base
has_many :conversation_users
has_many :conversations, through: :conversation_users
validates :name, presence: true
end
class BugTest < Minitest::Test
def test_conversation_with_valid_existing_user
user = User.create!(name: "North Bieber")
assert user.persisted?
conversation = Conversation.new(user_ids: [user.id])
conversation.save!
assert_equal 1, conversation.users.count
assert_equal [user], conversation.users
end
def test_conversation_with_invalid_existing_user
user = User.new()
user.save!(validate: false)
assert user.persisted?
# This test fails, even though Conversation should not be responsible for validating an associated existing record
conversation = Conversation.new(user_ids: [user.id])
conversation.save!
assert_equal 1, conversation.users.count
assert_equal [user], conversation.users
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment