habtm_destroy_order_test.rb 1.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
require "cases/helper"
require "models/lesson"
require "models/student"

class HabtmDestroyOrderTest < ActiveRecord::TestCase
  test "may not delete a lesson with students" do
    sicp = Lesson.new(:name => "SICP")
    ben = Student.new(:name => "Ben Bitdiddle")
    sicp.students << ben
    sicp.save!
    assert_raises LessonError do
      assert_no_difference('Lesson.count') do
        sicp.destroy
      end
    end
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
    assert !sicp.destroyed?
  end

  test "not destroying a student with lessons leaves student<=>lesson association intact" do
    # test a normal before_destroy doesn't destroy the habtm joins
    begin
      sicp = Lesson.new(:name => "SICP")
      ben = Student.new(:name => "Ben Bitdiddle")
      # add a before destroy to student
      Student.class_eval do
        before_destroy do
          raise ActiveRecord::Rollback unless lessons.empty?
        end
      end
      ben.lessons << sicp
      ben.save!
      ben.destroy
      assert !ben.reload.lessons.empty?
    ensure
      # get rid of it so Student is still like it was
      Student.reset_callbacks(:destroy)
    end
  end

  test "not destroying a lesson with students leaves student<=>lesson association intact" do
    # test a more aggressive before_destroy  doesn't destroy the habtm joins and still throws the exception
    sicp = Lesson.new(:name => "SICP")
    ben = Student.new(:name => "Ben Bitdiddle")
    sicp.students << ben
    sicp.save!
    assert_raises LessonError do
      sicp.destroy
    end
    assert !sicp.reload.students.empty?
50 51
  end
end