Testing with RSpec in Rails

Skip to first unread message

Sean Bowman

Dec 17, 2011, 3:22:36 PM12/17/11
to CouchRest
Maybe this is a silly question, because I haven't been able to find
anything in the documentation, issues, or Stack Overflow on what to do
about "transactioning" each test case in RSpec, particularly when
testing Rails CouchRest::Model::Base classes.

I know CouchDB doesn't support transactions, but when you're using a
relational database, RSpec will wrap each test case in a transaction
and roll the transaction back in the end, so the database is pristine
for the next test. How should I accomplish the equivalent of this
using CouchRest?

For example, I create a test case to ensure that a User object has a
login property, followed by a test that the login is unique:

describe User do

# Test Case A
it "should require a login" do
user = User.create :email => 'b...@nowhere.com', :password =>
'test', :password_confirmation => 'test'
user.errors.should include(:login)

user = User.create :login => 'bob', ...
user.errors.should be_empty
user.should be_valid
User.find_by_login('bob').should_not be_nil

# Test Case B
it "should ensure a unique login" do
user = User.create :login => 'bob', ...
user.should be_valid

user = User.create :login => 'bob', ...
user.should_not be_valid
user.errors.should include(:login)

If I run this as is, I'll get an error at the beginning of Test Case
B, when I create the first "bob", because that user is still there
from the end of Test Case A.

I've tried doing something like this:

after :each { User.database.delete! }

But then I get a 404 error message during Test Case B that the
database is missing. Apparently if I delete the database and try to
use it again, CouchRest or CouchRest::Model doesn't recreate it in the
same Ruby instance? Should I be doing this instead:

after :each { User.all.each(&:destroy) }

Is that the proper way to clean up the databases between tests? Or is
there something I'm missing?

Fernando Almeida

May 4, 2012, 3:44:57 AM5/4/12
to couc...@googlegroups.com
I'm using this:

# spec_helper.rb
RSpec.configure do |config|
  config.before(:each) do
    CouchRest::Model::Base.database.recreate! rescue nil

I don't know if is the best practice.
Reply all
Reply to author
0 new messages