Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add spec to confirm CTEs work as expected #205

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions spec/chrono_model/time_machine/with_cte_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
require 'spec_helper'

RSpec.describe ChronoModel::TimeMachine do
include ChronoTest::TimeMachine::Helpers

adapter.create_table 'posts', temporal: true do |t|
t.string :title
t.references :author
t.timestamps
end

adapter.create_table 'authors', temporal: true do |t|
t.string :name
t.timestamps
end

class Post < ActiveRecord::Base
include ChronoModel::TimeMachine

belongs_to :author
end

class Author < ActiveRecord::Base
include ChronoModel::TimeMachine
end

describe '.with CTE' do
let(:author1) { Author.create(name: author1_name_as_of_post1) }
let(:post1) { Post.create(title: 'Post 1', author: author1) }
let(:author2) { Author.create(name: 'Author 2') }
let(:post2) { Post.create(title: 'Post 2', author: author2) }

let(:author1_name_as_of_post1) { 'Author 1.1' }
let(:author1_name_as_of_post2) { 'Author 1.2' }
let(:author1_name_as_of_now) { 'Author 1.3' }

before do
post1
sleep(0.05)
author1.update(name: author1_name_as_of_post2)
post2
sleep(0.05)
author1.update(name: author1_name_as_of_now)
end

it 'works' do
# it does not automatically add as_of to CTE
scope = Post.as_of(post2.created_at)
.with(authors_cte: Author.all)
.joins("inner join authors_cte on authors_cte.id = posts.author_id")
expect(scope.where(authors_cte: { name: author1_name_as_of_now }).count).to eq(1)
expect(scope.where(authors_cte: { name: author1_name_as_of_post2 }).count).to eq(0)

# it produces an as_of CTE
scope = Post.as_of(post2.created_at)
.with(authors_cte: Author.as_of(post2.created_at).all)
.joins("inner join authors_cte on authors_cte.id = posts.author_id")
expect(scope.where(authors_cte: { name: author1_name_as_of_now }).count).to eq(0)
expect(scope.where(authors_cte: { name: author1_name_as_of_post2 }).count).to eq(1)
end
end
end