I am trying to refactor some RSpec/Rails tests so that they persist as few objects to the database as possible, but am having trouble trying to figure out how to re-write tests like the following:
describe User do
context "record creation" do
before(:each) { @user = User.new(user_atts) }
it "should generate a confirmation_token" do
# Generated as the result of a callback
@user.save!
expect(@user.confirmation_token).to be_present
end
it "should set the confirmed_at attribute to nil" do
# Cleared as the result of a callback
@user.save!
expect(@user.confirmed_at).to be_nil
end
it "should call the send_confirmation_instructions method" do
@user.should_receive(:send_confirmation_instructions) {}
@user.save!
end
end
def user_atts
# return attributes hash
end
end
This is a pretty simple example, but there are plenty of similar instances in my specs, and, for the most part, they all persist records to the database. I would love to take advantage of RSpec’s let and subject helpers, but am not fully sure that those would even help here.
I have been using FactoryGirl a lot and thought that maybe its build_stubbed strategy would speed up my specs a bit, but I couldn’t find many instances where it would help limit actual record creation (or maybe I don’t know how to use).
I assume there are some cases where a test requires record creation, but the above example hardly seems like one of them. Should I even be trying to refactor this or is there a better to write these tests? Any help would be greatly appreciated.
My tests would probably look something like this.
That’s using Factory Girl to create the user models. Also, I’d have DatabaseCleaner to clear the database after each test as stated by @RahulGarg
All you’d have to do is configure in your spec_helper something like this
This means after each test the Database would be cleared.