timpone
timpone

Reputation: 19929

does FactoryGirl create a record on every create; works from console not in rspec

I have the following code in a spec:

it 'should save some favorite locations' do
  user=FactoryGirl.create(:user)  # not adding anything

and it doesn't seem to write anything to the database. Is FactoryGirl intended to write something with this in a model spec? If I run from the rails console, it does add to the database. Why isn't a test in an rspec isn't running this? Is that how it is intended to work?

thx

Upvotes: 1

Views: 2389

Answers (1)

ronalchn
ronalchn

Reputation: 12335

If you have configured rspec to use database transactions for each test, or to use database truncation, then any records created are rolled back or destroyed.

To check that it really is adding something, you could try:

it 'should save some favorite locations' do
  user=FactoryGirl.create(:user)  # not adding anything
  User.find(user.id).should_not be_nil # ensure it is in database

If it passes, then it was added to the database.

If you are using database transactions for your tests, then the database is rolled back after each test. If you need to use a record which is created in multiple tests, you can use:

before(:all) do
  @user=FactoryGirl.create(:user)
end
after(:all) do
  @user.destroy # with create in before(:all), it is not in a transaction
                # meaning it is not rolled back - destroy explicitly to clean up.
end

Upvotes: 6

Related Questions