Reputation: 13626
I'm trying to extract a set of models from a Rails 3.2.3 app into a gem so they can be used as a shared interface between applications.
I moved the model into a module and put it in lib/invite_interface/invite.rb
module InviteInterface
class Invite < ActiveRecord::Base
belongs_to :user
end
def to_json; end;
def from_json; end;
end
I plopped rspec into the gemfile, got it running successfully, created the following spec:
require 'spec_helper'
describe InviteInterface::EncounterSurvey do
it 'should belong to user' do
subject.should respond_to(:user)
end
end
Unfortunately, I can't execute rspec on the model, because active record/rspec wants an active connection.
1) InviteInterface::Invite should belong to encounter survey set
Failure/Error: subject.should respond_to(:user)
ActiveRecord::ConnectionNotEstablished:
ActiveRecord::ConnectionNotEstablished
# /Users/justin/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:398:in `retrieve_connection'
# /Users/justin/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_specification.rb:168:in `retrieve_connection'
# /Users/justin/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_record/connection_adapters/abstract/connection_specification.rb:142:in `connection'
# /Users/justin/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_record/model_schema.rb:228:in `columns'
# /Users/justin/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_record/model_schema.rb:243:in `column_defaults'
How do I prevent ActiveRecord from looking for a DB connection?
Upvotes: 15
Views: 2959
Reputation: 5437
You need to test your library with a database anyway, so you might as well use an in-memory SQLite database for testing. Just add this to spec_helper.rb
:
ActiveRecord::Base.establish_connection(:adapter => "sqlite3",
:database => ":memory:")
and create your schema as follows:
ActiveRecord::Schema.define do
self.verbose = false
create_table :invites, :force => true do |t|
t.string :text
end
...
end
Upvotes: 13
Reputation: 759
I have found that if you are testing your models isolated, you may as well try to make use of SQLite3's in-memory capabilities when defining the ActiveRecord
connection to get very fast specs:
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => ':memory:'
)
Try it out, it worked like a charm for me and got my models tested much quicker.
Upvotes: 10