migration_generator_test.rb 2.6 KB
Newer Older
1
require 'generators/generators_test_helper'
2
require 'rails/generators/rails/migration/migration_generator'
3

4 5 6
class MigrationGeneratorTest < Rails::Generators::TestCase
  include GeneratorsTestHelper

7
  def test_migration
8 9 10
    migration = "change_title_body_from_posts"
    run_generator [migration]
    assert_migration "db/migrate/#{migration}.rb", /class ChangeTitleBodyFromPosts < ActiveRecord::Migration/
11 12
  end

13 14 15 16 17 18 19 20 21 22 23 24 25
  def test_migrations_generated_simultaneously
    migrations = ["change_title_body_from_posts", "change_email_from_comments"]

    first_migration_number, second_migration_number = migrations.collect do |migration|
      run_generator [migration]
      file_name = migration_file_name "db/migrate/#{migration}.rb"

      File.basename(file_name).split('_').first
    end

    assert_not_equal first_migration_number, second_migration_number
  end

26
  def test_migration_with_class_name
27 28 29
    migration = "ChangeTitleBodyFromPosts"
    run_generator [migration]
    assert_migration "db/migrate/change_title_body_from_posts.rb", /class #{migration} < ActiveRecord::Migration/
30 31 32
  end

  def test_add_migration_with_attributes
33 34
    migration = "add_title_body_to_posts"
    run_generator [migration, "title:string", "body:text"]
35

36
    assert_migration "db/migrate/#{migration}.rb" do |content|
37
      assert_class_method :up, content do |up|
38 39 40
        assert_match /add_column :posts, :title, :string/, up
        assert_match /add_column :posts, :body, :text/, up
      end
41

42
      assert_class_method :down, content do |down|
43 44 45
        assert_match /remove_column :posts, :title/, down
        assert_match /remove_column :posts, :body/, down
      end
46 47 48 49
    end
  end

  def test_remove_migration_with_attributes
50 51
    migration = "remove_title_body_from_posts"
    run_generator [migration, "title:string", "body:text"]
52

53
    assert_migration "db/migrate/#{migration}.rb" do |content|
54
      assert_class_method :up, content do |up|
55 56 57
        assert_match /remove_column :posts, :title/, up
        assert_match /remove_column :posts, :body/, up
      end
58

59
      assert_class_method :down, content do |down|
60 61 62
        assert_match /add_column :posts, :title, :string/, down
        assert_match /add_column :posts, :body, :text/, down
      end
63 64
    end
  end
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

  def test_should_create_empty_migrations_if_name_not_start_with_add_or_remove
    migration = "create_books"
    run_generator [migration, "title:string", "content:text"]

    assert_migration "db/migrate/#{migration}.rb" do |content|
      assert_class_method :up, content do |up|
        assert_match /^\s*$/, up
      end

      assert_class_method :down, content do |down|
        assert_match /^\s*$/, down
      end
    end
  end
80
end