aboutsummaryrefslogtreecommitdiffstats
path: root/railties/test/application/loading_test.rb
blob: ecf7904c391d6ac69cf9a3293575ab7f4638ab31 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
require 'isolation/abstract_unit'

class LoadingTest < Test::Unit::TestCase
  include ActiveSupport::Testing::Isolation

  def setup
    build_app
    boot_rails
  end

  def app
    @app ||= Rails.application
  end

  def test_constants_in_app_are_autoloaded
    app_file "app/models/post.rb", <<-MODEL
      class Post < ActiveRecord::Base
        validates_acceptance_of :title, :accept => "omg"
      end
    MODEL

    require "#{rails_root}/config/environment"
    setup_ar!

    p = Post.create(:title => 'omg')
    assert_equal 1, Post.count
    assert_equal 'omg', p.title
    p = Post.first
    assert_equal 'omg', p.title
  end

  def test_models_without_table_do_not_panic_on_scope_definitions_when_loaded
    app_file "app/models/user.rb", <<-MODEL
      class User < ActiveRecord::Base
        default_scope where(:published => true)
      end
    MODEL

    require "#{rails_root}/config/environment"
    setup_ar!

    User
  end

  def test_descendants_are_cleaned_on_each_request_without_cache_classes
    add_to_config <<-RUBY
      config.cache_classes = false
    RUBY

    app_file "app/models/post.rb", <<-MODEL
      class Post < ActiveRecord::Base
      end
    MODEL

    app_file 'config/routes.rb', <<-RUBY
      AppTemplate::Application.routes.draw do |map|
        match '/load',   :to => lambda { |env| [200, {}, Post.all] }
        match '/unload', :to => lambda { |env| [200, {}, []] }
      end
    RUBY

    require 'rack/test'
    extend Rack::Test::Methods

    require "#{rails_root}/config/environment"
    setup_ar!

    assert_equal [], ActiveRecord::Base.descendants
    get "/load"
    assert_equal [Post], ActiveRecord::Base.descendants
    get "/unload"
    assert_equal [], ActiveRecord::Base.descendants
  end

  protected

  def setup_ar!
    ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
    ActiveRecord::Migration.verbose = false
    ActiveRecord::Schema.define(:version => 1) do
      create_table :posts do |t|
        t.string :title
      end
    end
  end
end