Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'rubygems'
- require 'active_record'
- ActiveRecord::Base.establish_connection({
- :adapter => 'mysql',
- :database => 'spike',
- :username => 'root',
- :password => '',
- :encoding => 'utf8'
- })
- ActiveRecord::Schema.define do
- create_table :children, :force => true do |t|
- t.column :parent_id, :integer
- end
- create_table :parents, :force => true do |t|
- t.column :name, :integer
- end
- execute %{alter table children add constraint
- fk_children_parents foreign key (parent_id)
- references parents(id)}
- end
- class Child < ActiveRecord::Base
- belongs_to :parent
- end
- class Parent < ActiveRecord::Base
- end
- class FKChecksTest < Test::Unit::TestCase
- def setup
- @parent = Parent.create
- @child = Child.create(:parent_id => @parent.id)
- end
- def with_fk_checks_off
- ActiveRecord::Base.connection.update('SET FOREIGN_KEY_CHECKS = 0')
- yield
- ActiveRecord::Base.connection.update('SET FOREIGN_KEY_CHECKS = 1')
- end
- def test_expect_deleting_target_of_foreign_key_raises
- assert_raises(ActiveRecord::StatementInvalid) {@parent.destroy}
- assert !@parent.frozen?
- assert !@child.reload.parent.nil?
- end
- def test_deleting_with_fk_checks_off
- with_fk_checks_off { @parent.destroy }
- assert @parent.frozen?
- assert @child.reload.parent.nil?
- end
- def test_with_fk_checks_off_cleans_up
- parent2 = Parent.create
- child2 = Child.create(:parent_id => parent2.id)
- with_fk_checks_off { @parent.destroy }
- assert_raises(ActiveRecord::StatementInvalid) {parent2.destroy}
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement