aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases/statement_cache_test.rb
blob: 76da49707f32ac521a583b6fd9631033a467126c (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
require 'cases/helper'
require 'models/book'
require 'models/liquid'
require 'models/molecule'
require 'models/electron'

module ActiveRecord
  class StatementCacheTest < ActiveRecord::TestCase
    def setup
      @connection = ActiveRecord::Base.connection
    end

    def test_statement_cache_with_simple_statement
      cache = ActiveRecord::StatementCache.new do
        Book.where(name: "my book").where("author_id > 3")
      end

      Book.create(name: "my book", author_id: 4)

      books = cache.execute
      assert_equal "my book", books[0].name
    end

    def test_statement_cache_with_nil_statement_raises_error
      assert_raise(ArgumentError) do
        ActiveRecord::StatementCache.new do
          nil
        end
      end
    end

    def test_statement_cache_with_complex_statement
      cache = ActiveRecord::StatementCache.new do
        Liquid.joins(:molecules => :electrons).where('molecules.name' => 'dioxane', 'electrons.name' => 'lepton')
      end

      salty = Liquid.create(name: 'salty')
      molecule = salty.molecules.create(name: 'dioxane')
      molecule.electrons.create(name: 'lepton')

      liquids = cache.execute
      assert_equal "salty", liquids[0].name
    end

    def test_statement_cache_values_differ
      cache = ActiveRecord::StatementCache.new do
        Book.where(name: "my book")
      end

      3.times do
        Book.create(name: "my book")
      end

      first_books = cache.execute

      3.times do
        Book.create(name: "my book")
      end

      additional_books = cache.execute
      assert first_books != additional_books
    end
  end
end