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()
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:
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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With