Skip to content

Instantly share code, notes, and snippets.

@puyo
Created August 26, 2011 08:08
Show Gist options
  • Save puyo/1172955 to your computer and use it in GitHub Desktop.
Save puyo/1172955 to your computer and use it in GitHub Desktop.
Is it possible to rspec this properly without hitting the database?
create_table "line_items", :force => true do |t|
t.integer "cost"
t.boolean "paid"
t.integer "order_id"
end
create_table "orders", :force => true do |t|
end
# -----
class LineItem < ActiveRecord::Base
scope :paid, where(:paid => true)
end
# -----
class Order < ActiveRecord::Base
has_many :line_items
def total_cost
line_items.paid.sum(:cost)
end
end
# -----
require 'spec_helper'
describe Order do
let(:order) { Order.new(:line_items => line_items) }
describe '#total_cost' do
subject { order.total_cost }
context 'with line items costing 2 and 3 and 4 (unpaid)' do
before { order.save! }
let(:line_items) {
[
LineItem.new(:cost => 2, :paid => true),
LineItem.new(:cost => 3, :paid => true),
LineItem.new(:cost => 4, :paid => false),
]
}
it { should == 5 }
end
context 'with no line items' do
let(:line_items) { [] }
it { should == 0 }
end
end
end
@scottharvey
Copy link

I like the idea of creating a gem that allows you to do in memory AREL queries. If it could also allow you to test ActiveRecord callbacks without saving that would be nice as well.

@puyo
Copy link
Author

puyo commented Sep 5, 2011

That sounds pretty challenging but if it passed the AREL test suite (I haven't looked into it but I assume it has one and that it is reasonably complicated), then it would seem reasonable enough to run your unit tests against that instead of the database.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment