Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()

  • The rails console says that the object is persisted to the database (as expected)
  • The test/test.log show that the object was persisted to the database (as expected)
  • But when I look at the table within the test database: It is not there (not expected. I would expect to see the object within the database)

    #someApp/spec/models/user_spec.rb
    RSpec.describe User, type: :model do
      it "checks the age on the basic 'User' Factory " do
        user = create(:user) # should create a user and persist it to the database
        binding.pry
        expect(user.age).to eq(28)
      end
    end
    

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?

like image 262
Neil Avatar asked Dec 14 '22 09:12

Neil


1 Answers

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)

like image 54
Mike Szyndel Avatar answered Dec 30 '22 08:12

Mike Szyndel