Neil
Neil

Reputation: 5188

Creating a record does not appear to persist to the test database, rspec, factory_girl_rails

According to the factory_girl_rails documentation: here is the difference between the factory_girl build() and create() methods:

# Returns a User instance that's not saved

user = build(:user)

# Returns a saved User instance

user = create(:user)

I know the power of factories is that they make your test suite fast because it allows you to run tests without having to touch the database at all via the build() method. The create() method on the other hand does still touch the database because it persists the record to the database.

I am confused because when I put a break point within my test after using create()

Execution stops at the break point and the rails console opens up. I test for persistence and it returns true:

user.persisted? 
  => true

However, I look within my test database at the table, refresh the table, and yet still no record is shown:

record does not display in table

What am I missing? I thought that when you use create() the record will be persisted to the database. Does it actually not save to the database at all?

Upvotes: 4

Views: 4522

Answers (1)

Mike Szyndel
Mike Szyndel

Reputation: 10592

RSpec runs tests in transactions. This means that before a test starts a transaction is opened and after the test is done it's rolled back. This way the test interfaces with the DB but no data is visible from outside the transaction (so from outside RSpec process)

Upvotes: 12

Related Questions