I am running rails db:reset db:migrate
in between tests from within my testing script (which imports and interfaces with the model directly), but the changes are not reflected between the first test and the second test. More specifically, the changes caused by the first test are not reversed as they should be.
When I connect to the database externally (from the shell), I observe that the command has taken effect.
I have already looked at this question but the solution had no effect (quite literally, there was no error but also no discernible effect).
How can I force my test script to clear its in-memory cache of the sqlite state?
Create a new rails app.
rails new MWE
Put the following in db/schema.rb
ActiveRecord::Schema.define(version: 20140408213603) do create_table "users", force: true do |t| t.string "username" end end
Put the following in db/seed.rb
.
User.create(username: 'user1') User.create(username: 'user2') User.create(username: 'user3')
Put the following in the Gemfile
.
source 'https://rubygems.org' gem 'rails', '4.0.0' gem 'sqlite3' gem 'protected_attributes'
Put the following in a file called app/models/user.rb
.
class User < ActiveRecord::Base attr_accessible :username end
Run the following commands.
bundle install rake db:reset
Place the following contents in a file called MWE.rb
load 'config/application.rb' load 'config/environment.rb' load 'app/models/user.rb' # Mimic the unsafe call in the source code system("bundle exec rake db:reset") puts User.count User.destroy_all("username = 'user3'") puts User.count system("bundle exec rake db:reset") puts User.count User.destroy_all("username = 'user3'") puts User.count
Run the file and observe actual output .
$ ruby MWE.rb -- create_table("users", {:force=>true}) -> 0.0362s -- initialize_schema_migrations_table() -> 0.0248s 3 2 -- create_table("users", {:force=>true}) -> 0.0809s -- initialize_schema_migrations_table() -> 0.0490s 2 2
-- create_table("users", {:force=>true})
-> 0.0362s
-- initialize_schema_migrations_table()
-> 0.0248s
3
2
-- create_table("users", {:force=>true})
-> 0.0809s
-- initialize_schema_migrations_table()
-> 0.0490s
3
2
How can I force the DB reset to be reflected in the model?
All you need to do is to reestablish database connection. Try:
system("bundle exec rake db:reset")
puts User.count
User.destroy_all("username = 'user3'")
puts User.count
system("bundle exec rake db:reset")
ActiveRecord::Base.clear_all_connections!
puts User.count
User.destroy_all("username = 'user3'")
puts User.count
The main question is: why do you need to do this? I am pretty certain there is a better way to achieve what you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.