On Jan 26, 7:09 pm, Robbie Clutton <[email protected]> wrote: > Hi, > > I've got a Rails app and I'd like to introduce the nulldb adapter to ensure > the type:model tests do not hit the database. I do want an exception for > when I test scopes or other complex queries. Is there anyway to have two > conflicting configuration before blocks, something like: > > describe MyModel do > it 'tests scopes', db: true > ... > end > > it 'tests something else' do > ... > end > end > > config.before(type: :model, db: true) do > # use real database > end > > config.before(type: :model, unless: db) do > # use nulldb > end > > cheers > > Robbie
The simplest way to get this kind of conditional behavior is to use a global before hook that inspects example metadata to know what to do. VCR has an example of this: https://github.com/vcr/vcr/blob/v2.4.0/spec/spec_helper.rb#L61-L67 That said, I've used NullDB on a project before, and I got the semantics you want with a slightly different method: RSpec.configure do |config| # Use NullDB by default config.before(:suite) do ActiveRecord::Base.establish_connection(:adapter => :nulldb) end config.after(:suite) do ActiveRecord::Base.establish_connection(:test) end # Use the real DB for any specs tagged with :real_db => true. # Note that this only works when you tag an example group, not an individual example. config.before(:all, :real_db => true) do ActiveRecord::Base.establish_connection(:test) end config.after(:all, :real_db => true) do ActiveRecord::Base.establish_connection(:adapter => :nulldb) end end Note that this approach uses before/after :all hooks, which I generally recommend against using, but actually makes sense here. The AR DB connection is a global anyway (so you're not starting with a clean AR connection slate in each example), and in the past, the setup/ teardown of the AR DB connection has been surprisingly slow. (That may have been fixed in recent rails releases). Using :all hooks limits the number of times the connection has to be setup and torn down. Note, however, that with this approach you have to tag the example group with `:real_db => true`, not individual examples, because `before(:all)` applies only to example groups, not examples. HTH, Myron -- You received this message because you are subscribed to the Google Groups "rspec" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit https://groups.google.com/groups/opt_out.
