Created
February 18, 2015 21:12
-
-
Save kaikuchn/0a1a9b4a67f177c0ddf1 to your computer and use it in GitHub Desktop.
Reproducing Test for replacing has_one relation with uniqueness constraint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
unless File.exist?('Gemfile') | |
File.write('Gemfile', <<-GEMFILE) | |
source 'https://rubygems.org' | |
gem 'rails', github: 'rails/rails' | |
gem 'arel', github: 'rails/arel' | |
gem 'rack', github: 'rack/rack' | |
gem 'i18n', github: 'svenfuchs/i18n' | |
gem 'sqlite3' | |
GEMFILE | |
system 'bundle' | |
end | |
require 'bundler' | |
Bundler.setup(:default) | |
require 'rails' | |
require 'active_record' | |
require 'minitest/autorun' | |
require 'rack/test' | |
class Arm < ActiveRecord::Base | |
belongs_to :bandit, inverse_of: :arm | |
# instead of validating this here, you could also add a uniqueness | |
# constraint through a migration. Behavior would be similiar. | |
validates :bandit, uniqueness: true | |
end | |
class Bandit < ActiveRecord::Base | |
has_one :arm, dependent: :destroy, inverse_of: :bandit | |
end | |
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') | |
migration = ActiveRecord::Migration.new | |
migration.create_table :bandits do |table| | |
table.timestamps null: false | |
end | |
migration.create_table :arms do |table| | |
table.references :bandit | |
table.timestamps null: false | |
end | |
class ReplacingHasOneRelationWithUniquenessConstraintTest < Minitest::Test | |
include Rack::Test::Methods | |
def setup | |
@bandit = Bandit.create! | |
@bandit.create_arm! | |
end | |
def test_create_arm_should_replace_arm | |
@bandit.create_arm! | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment