Rails Rspec - ActiveRecord::StatementInvalid: PG::InFailedSqlTransaction: - ruby-on-rails

I have this controller method
def dashboard
method1
method2
method3
..
end
Everything is working fine in development environment..
but in test environment,
i am getting this error after first few methods.
I checked using binding.pry just above the line which i used to get error,
I cannot run any query eg: Account.first
but same Account.first works in dev environment
Error when i run in test environment:
ActiveRecord::StatementInvalid: PG::InFailedSqlTransaction: ERROR: current transaction is aborted, commands ignored until end of transaction block
: SELECT "accounts".* FROM "accounts" ORDER BY "accounts"."id" ASC LIMIT 1
from /home/qwinix/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-4.2.4/lib/active_record/connection_adapters/postgresql_adapter.rb:596:in `async_exec'
Please note the following
No erros found in other controllers and respective spec.
There was no error in the same controller from other branch
I added few code to method1, which executes just fine in both environment. i am getting these error after method3 which i havent touched.
PS: I did google and search stackoverflow questions, didnt help
Edit: When i moved the method1 to end, i am not getting any errors, please explain me this behaviour.

Did you try to reset the Test Database?
bundle exec rails db:drop RAILS_ENV=test
bundle exec rails db:create RAILS_ENV=test
bundle exec rails db:schema:load RAILS_ENV=test
or for Rails Version older than 5
bundle exec rake db:drop RAILS_ENV=test
bundle exec rake db:create RAILS_ENV=test
bundle exec rake db:schema:load RAILS_ENV=test
or shorter:
bundle exec rake db:reset RAILS_ENV=test

Related

Migration not executed from rspec

I created the following migration script (using bundle exec rails generate migration CreateSequenceStudentId):
class CreateSequenceStudentId < ActiveRecord::Migration[6.0]
def change
# Based on: https://schmijos.medium.com/execute-sql-in-rails-migrations-cdb26f51c683
execute 'CREATE SEQUENCE IF NOT EXISTS student_id;'
end
end
Then executed bundle exec rails db:migrate RAILS_ENV=test and it completed. I can access the sequence using psql student_test -c"select nextval('student_id')". Running psql student_test -c"select * from schema_migrations sm" lists 20201122013457 at the very last. No problems so far.
I then wrote the following spec to access the sequence:
sql = "select nextval('student_id')"
p Student.connection.select_all(sql)
And it failed:
# --- Caused by: ---
# PG::UndefinedTable:
# ERROR: relation "student_id" does not exist
# LINE 1: select nextval('student_id')
And I executed psql student_test -c"select nextval('student_id')" one more time and got:
ERROR: relation "student_id" does not exist
LINE 1: select nextval('student_id')
bundle exec rails db:migrate:status RAILS_ENV=test gives:
Status Migration ID Migration Name
--------------------------------------------------
...
up 20201122013457 Create sequence student
So it indicates the migration executed successfully.
psql student_test -c"select * from schema_migrations sm" gives:
version
----------------
20201122013457
20191209013052
20191220005953
20191225001051
20191225001255
20191225001458
...
The new script was executed first. This smells fishy.
Sounds like the migration ran successfully when using db:migrate but not when running rspec. Appreciate any pointers on what I could be doing wrong.
PS: Based on this solution, I have checked if the script name is unique and it is.
I was able to fix your issue by running exact below commands. I found the answer here.
RAILS_ENV=test rake db:drop
RAILS_ENV=test rake db:create
RAILS_ENV=test rake db:migrate
UPDATE:
I found also the way to fix rails db:reset command, you just need to add line config.active_record.schema_format = :sql in your application.rb so info about sequence will be stored in structure.sql. Please take a look that with default schema dump :ruby info about seqeunce is not stored in schema.rb file.
Important: make sure to firstly create structure.sql with rails db:migrate and then run rails db:reset. After just rails db:migrate I'm still getting the error you want to fix.

rails test database cloning dev database

I'm new to Ruby on Rails and following Michael Hartls Ruby on Rails Tutorial. When I run bundle rake exec test, I am getting this error:
ERROR["test_should_get_new", SessionsControllerTest, 2.331314]
test_should_get_new#SessionsControllerTest (2.33s)
ActiveRecord::StatementInvalid:
ActiveRecord::StatementInvalid: Could not find table 'users'
and once similar for all of my tests. I see that my test database: test.sqlite3 is empty. My development database development.sqlite3 does have the users table in it.
I tried running the following to attempt cloning the users database to the test database, but nothing is working:
rake db:migrate:reset
rake db:migrate db:test:prepare
rake db:test:clone
rake db:test:prepare
rake db:test:load
but it's still empty. Any suggestions please?
I think you might be able to get it with:
RAILS_ENV=test rake db:migrate
Give it a try, I've had this problem before myself. I believe that
rake db:test:prepare
is deprecated. What version of ruby and rails are you using?
I figured out a fix, although I'm still not sure why there was a problem to begin with. What I did was I took the pure Sql CREATE TABLE used to create the development table and executed it in the users table. Now everything is working fine.

How to resolve Rails ActiveRecord::PendingMigrationError?

When I try to load a page of my site, I get:
ActiveRecord::PendingMigrationError Migrations are pending.
To resolve this issue, run: bin/rake db:migrate RAILS_ENV=development
But when I when I run rake db:migrate I get:
SQLite3::SQLException table "options" already exists...
Running rake db:reset doesn't fix anything either. Trying to load a page still gives me the PendingMigrationError.
If instead I run rake db: drop and then rake db:migrate, I get this:
rake aborted
Standard Error! An error has occured, this and all later migrations canceled.
undefined method 'can_pick_many_options' ....
Note: I'm running Rails 4.1.2

Getting: "Migrations are pending; run 'bin/rake db:migrate RAILS_ENV=development' to resolve this issue." after cloning and migrating the project

I cloned my project. Bundled with "bundle install", then run "rake db:migrate". I am getting this error: (when I run the rails server and open my browser to localhost:3000) "Migrations are pending; run 'bin/rake db:migrate RAILS_ENV=development' to resolve this issue."
I checked all migrations one by one and all were executed without errors. Also no errors were shown after the execution of "rake db:migrate".
This is what I see when I execute "rake db:migrate:status"
I am on development environment. Please let me know if you need any other information.
I also tried "bundle exec rake db:migrate", and "bundle exec rake db:migrate:reset" as "burninggramma" suggested.
Any clues what causes the error?
Interesting. Did you run rake db:create? Assuming you are using sqlite3, do this:
rm -f db/*.sqlite3
rake db:create
RAILS_ENV=development bundle exec rake db:migrate
rails s -e development
Also, can you list the contents of your config/database.yml file?
Edit: Warning! Obviously, you will lose your existing data.
After running the migrate command, I still had the same error.
What worked for me was to just stop the rails server and start it again.
List your executed migrations with rake db:migrate:status and look if every migration was executed. You can try to cancel your migration with rake db:abort_if_pending_migrations and try to migrate again.
1. Maybe its default in ruby2/rails4 but have you tried: bundle exec rake db:migrate?
2. Another option would be resetting the whole database - use with CAUTION! resets all the data as well - bundle exec rake db:migrate:reset
+) I would just make sure that you are executing everything in the same development env:
RAILS_ENV=development bundle exec rake db:migrate:reset
RAILS_ENV=development bundle exec rails s
Running rake db:migrate RAILS_ENV=test did it for me
I had the same error in the browser, but upon closely looking at the error message, I noticed some how I had an extra white space in the migrate comment and post files. Once I removed it, it worked perfectly.
Open the database and click schema_migration table. The migrations will be listed as below.
Sort the version column and find the latest migration you want to go back. Delete or Insert a new one. Rails keeps all the migration history in this table, so you can adjust the migration history to you liking.
I got the same error working on the Learn Enough to Be Dangerous Rails tutorial. I'm using Git Bash terminals on a Windows 10 machine. The error showed up in the terminal where I'm running guard, after I tried to migrate my db using the command (in another terminal):
$ bundle exec rake db: migrate:
After trying the solution offered by #lewstherin, I still got the same error. I tried the command:
$ rails test
And got the explicit and helpful warning:
Migrations are pending. To resolve this issue, run:
bin/rails db:migrate RAILS_ENV=test
I ran the command:
$ bin/rails db:migrate RAILS_ENV=test
and now I'm working again.
For me i just had to migrate for the error:
rake db:migrate --trace
By setting false to config.active_record.migration_error in development.rb might make it workable but i wouldn't recommend it.
Here's what worked for me:
-gem install rails -v 4.1.0
Inside Gemfile:
-gem 'rails', '4.1.0'
(replace the newer/older with this)
Do bundle install and update
-bundle install
-bundle update
In your application.rb :
Remove/Comment - config.active_record.raise_in_transactional_callbacks = true
run bundle rake:
-bundle exec rake db:migrate
Refresh your page and the error should be gone.
Two reasons 'db:migrate:reset' did not work for me
1) loosing data
2) we moved from php to rails, so we had an existing DB and the migrations were written on top of it not from the scratch
So What I tried is to update the 'scheema_migrations'(mysql) table with the list of migrations(just version values) that I was really sure were already run on my db(development), this can be lil time consuming process but it works. I would not attempt this on production though.
I'm guessing the error is that you are creating a table that already exists, I had this problem before.
Step 1
look into the error when you rake dv:migrate
Step 2
go to the model where this table is created
Step 3
add drop_table :[YOUR TABLE] right before the create_table :[YOUR TABLE]
Step 2
run rake db:migrate
Step 3
remove the drop_table once the your migration is done
I had the same problem in genieacs and this code helped:
rake db:drop rake db:create rake db:schema:load RAILS_ENV=development
rake db:migrate rails s -e development
You can always run rake db:reset

Migrations are pending; run 'bin/rake db:migrate RAILS_ENV=development' to resolve this issue [unable to proceed]

I appear to have a circular issue in regards to Ruby on Rails migration procedure. I am following the introduction article and I have reached the point when I need to create my first table.
I have ran the following,
[tims#web2 working_ror]# rails generate model Homepage first_name:string last_name:string email:string message:text
invoke active_record
create db/migrate/20131119203948_create_homepages.rb
create app/models/homepage.rb
invoke test_unit
createtest /models/homepage_test.rb
createtest /fixtures/homepages.yml
I then proceeded with the migration,
[tims#web2 working_ror]# rake db:migrate
== CreateHomepages: migrating ================================================
-- create_table(:homepages)
-> 0.0493s
== CreateHomepages: migrated (0.0494s) =======================================
, however, when I run my application I see the following message,
Migrations are pending; run 'bin/rake db:migrate RAILS_ENV=development' to resolve this issue.
but, IF I run the above,
[tims#web2 working_ror]# rake db:migrate RAILS_ENV=development
[tims#web2 working_ror]#
and the message continues ...
I have spent considerable amount of time researching forums in-which the closest I could find was to drop and re-build everything, which have done the following.
rake db:drop
rake db:create
rake db:migrate
and the results are the same.
You need to do
bundle exec rake test:prepare
or
bundle exec rake db:test:prepare
and then
bundle exec rake db:migrate
before running the specs
Cheers
cited from : Why am I asked to run 'rake db:migrate RAILS_ENV=test'?
you can do
bundle exec rake test:prepare
In Rails 4.1+, they deprecated db:test:prepare
You can now just use:
ActiveRecord::Migration.maintain_test_schema!
If you need to do it manually
rake db:schema:load RAILS_ENV=test
and then
bundle exec rake db:migrate
try
In RAILS_ROOT/config/environments/development.rb Set the following setting to false:
config.active_record.migration_error = false#:page_load
One weird trick that you can use when your migrations are screwed (file deleted, manually renamed, etc.)
Fire up your favourite DB admin tool (eg. PGAdmin3) and browse to the database in question.
Look for a table called schema_migrations and browse its content. It should have a single column called version. This field is used by Rails to check whether migrations are up to date.
Make sure that your migration timestamps corresponds with the data in this column. If you have deleted an older migration, delete the corresponding timestamp.
Check to make sure that table doesn't already exist:
type - rails dbconsole
type - .tables (check to see if there was an error during the rake db:migrate that has the table name like -- create_table(:test) rake aborted!)
If you see the table name after running the .tables in the console type - drop table TABLENAME;
Then .quit to go back to the branch and run the rake db:migrate command again.
this was what i did:
rails db:environment:set RAILS_ENV=test
If you need to do it manually
rake db:schema:load RAILS_ENV=test
and then
bundle exec rake db:migrate
Thanks to Ahmed Ali....... your comment was helpful.

Resources