Skip to content

Commit

Permalink
nicer ActiveRecord connection checking
Browse files Browse the repository at this point in the history
  • Loading branch information
nakajima committed Dec 30, 2008
1 parent 1d20a9b commit 3394ce7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 20 deletions.
20 changes: 10 additions & 10 deletions lib/acts_as_fu/helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ class << self
def connect!(config={})
@log = ""
ActiveRecord::Base.logger = Logger.new(StringIO.new(log))
ActiveRecord::Base.connection.disconnect! rescue nil
ActiveRecord::Base.establish_connection(config)
end
end

def build_model(name, options={}, &block)
connect!
connect! unless connected?

super_class = options[:superclass] || begin
ActiveRecord::Base.connection.create_table(name, :force => true) { }
Expand All @@ -33,15 +34,14 @@ def set_class!(name, super_class, &block)
end

def connect!
begin
# This blows up if there's no connection
ActiveRecord::Base.connection
rescue
ActsAsFu.connect!({
:adapter => "sqlite3",
:database => ":memory:"
})
end
ActsAsFu.connect!({
:adapter => "sqlite3",
:database => ":memory:"
})
end

def connected?
ActiveRecord::Base.connected?
end

def model_eval(klass, &block)
Expand Down
33 changes: 23 additions & 10 deletions spec/acts_as_fu_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,19 @@
describe ActsAsFu do
include ActsAsFu

def build_foos
def create_models
build_model(:foos) do
string :name
integer :age

def self.awesome?; true end
end

build_model(:bars) do
integer :foo_id

belongs_to :foo
end
end

describe "without building a model" do
Expand All @@ -22,7 +28,7 @@ def self.awesome?; true end

describe "after building a model" do
before(:each) do
build_foos
create_models
end

it "creates the class" do
Expand Down Expand Up @@ -61,7 +67,7 @@ def self.awesome?; true end

it "clears the table" do
Foo.count.should == 5
build_foos
create_models
Foo.count.should == 0
end

Expand All @@ -70,7 +76,7 @@ class << Foo; attr_reader :bar end

proc { Foo.bar }.should_not raise_error

build_foos
create_models

proc {
Foo.bar
Expand All @@ -97,26 +103,33 @@ class << Foo; attr_reader :bar end
end

describe "custom DB config" do
attr_reader :db

before(:each) do
system("rm -rf #{db}")
@db = "#{File.dirname(__FILE__)}/tmp.sqlite3"
end

it "allows connection to custom DB config" do
db = "#{File.dirname(__FILE__)}/tmp.sqlite3"

ActsAsFu.connect! \
:adapter => 'sqlite3',
:database => db

build_model(:acts) do
build_model(:others) do
string :body
end

File.exists?(db).should be_true

system("rm #{db}")
end

after(:each) do
system("rm -rf #{db}")
end
end

describe "ActsAsFu.report!" do
it "has a log" do
build_foos
create_models
ActsAsFu.log.should include("CREATE TABLE")
end
end
Expand Down

0 comments on commit 3394ce7

Please sign in to comment.