eval File.read(file_location) get error in rspec - ruby-on-rails

in my rspec testing, i have code like this
it 'test'
plan_calcs_from_file = File.read(file_location)
eval(plan_calcs_from_file)
end
but when i try to "eval(plan_calcs_from_file)", i get error like this
ActiveRecord::StatementInvalid Exception: Mysql2::Error: SAVEPOINT active_record_1 does not exist: ROLLBACK TO SAVEPOINT active_record_1
When i try in development mode this code work fine but in test mode this code get error. Why?

Try adding config.use_transactional_fixtures = false into the spec_helper.rb
You are using Mysql DDE statements (create/drop/truncate table) which will result in an implicit commit.
Because of the implicit commit, all savepoints of the current transaction are deleted.

Related

How do I decrypt in rails?

Hello fellow developers,
I have been stuck on this isssue for quite sometime now. All I want to do is somehow decrypt a column (ssn_or_ein) in my table (candidates) which was previously encrypted by the gem crypty_keeper.
https://github.com/jmazzi/crypt_keeper
What i have tried so far:
required the gem in Rails C and used the decrypt_table! against my Model
However, I am unable to catch the method
[pry(main)> Candidate.decrypt_table!
(0.2ms) BEGIN
Load (12.1ms) SELECT "candidates".* FROM "candidates" ORDER BY "candidates"."id" ASC LIMIT $1 [["LIMIT", 1000]]
(4.8ms) ROLLBACK
NameError: undefined local variable or method `crypt_keeper_fields' for #<Class:0x0000000007c5f038>
Did you mean? crypt_keeper
Also tried putting the pre-existing code back in my Application
class Candidate < ApplicationRecord
crypt_keeper :gateway_token, :ssn_or_ein, :e_in, encryptor: :active_support, key: ENV['ENCRYPTION_KEY'], salt: ENV['ENCRYPTION_SALT']
and I get an Active Support error
pry(main)> Candidate.decrypt_table!
(0.3ms) BEGIN
Load (609.8ms) SELECT "candidates".* FROM "candidates" ORDER BY "candidates"."id" ASC LIMIT $1 [["LIMIT", 1000]]
(0.3ms) ROLLBACK
ActiveSupport::MessageEncryptor::InvalidMessage: ActiveSupport::MessageEncryptor::InvalidMessage
from /home/niketa/.rvm/gems/ruby-2.6.7#raisethemoney5.2.5/gems/activesupport-5.2.6/lib/active_support/message_encryptor.rb:206:in `rescue in _decrypt'
Caused by ArgumentError: invalid base64
This is the error i am getting.
Any help or insight would be appreciated. Thanks
It looks like you have rows in your table that are not encrypted and those cause the Candidate.decrypt_table! call to fail. Did you maybe remove the crypt_keeper line from the Candidate class and then add entries? If so you'll have to remove them or skip them...

How to rollback failed transaction in rails console with pry

When trying out new active_record queries in the rails console with pry loaded, if a query causes an exception, I often have to stop the console and start it again, otherwise all queries cause an exception. I did have some code which appeared to fix this:
# .pryc
Pry.config.exception_handler = proc do |output, exception, _pry_|
output.puts "#{exception.class}: #{exception.message}"
output.puts exception.backtrace.first
if exception.instance_of?(ActiveRecord::StatementInvalid) && exception.original_exception.is_a?(PG::Error)
output.puts 'Rolling back transaction and starting a new one!'
connection = ActiveRecord::Base.connection
connection.rollback_db_transaction
connection.begin_db_transaction
end
end
but it appears to have stopped working in rails 5. The problem appears to be that exception.original_exception now raises this error
<NoMethodError: undefined method `original_exception' for #<ActiveRecord::StatementInvalid:0x00007fd2ceb4ba10>>
How do I fix this?

Could not log "sql.active_record" event. NoMethodError: undefined method `name'

I am currently developing an application using NuoDB and Ruby on Rails
I am using the 'nuodb' gem and the 'activerecord-nuodb-adapter' to connect to the DB but I seem to be getting an error with the logs when executing commands.
For example, when I run the commands in my action:
x = GeneralLedger.where("id = ?", params[:id]).first
x.delete
This would output in the development logs:
[1m[35mGeneralLedger Load (2.4ms)[0m SELECT `general_ledgers`.* FROM `general_ledgers` WHERE (id = '48') FETCH FIRST 1 ROWS ONLY
[1m[35mSQL (0.3ms)[0m DELETE FROM `general_ledgers` WHERE `general_ledgers`.`id` = 48
This is okay, but when I execute the more direct approach which is:
GeneralLedger.find(params[:id]).delete
I keep get this error:
Could not log "sql.active_record" event. NoMethodError: undefined method `name' for 48:Fixnum <------ error
[1m[35mSQL (0.4ms)[0m DELETE FROM `general_ledgers` WHERE `general_ledgers`.`id` = 48
Here's another example of the log error I get when I am updating existing records:
Could not log "sql.active_record" event. NoMethodError: undefined method `name' for 21:Fixnum
[1m[36m (0.1ms)[0m [1mbegin transaction[0m
[1m[35m (0.4ms)[0m UPDATE `general_ledgers` SET `accnt_dscr` = 'Other Expenses', `updated_at` = '2014-03-03 14:10:26' WHERE `general_ledgers`.`id` = 21
[1m[36m (0.3ms)[0m [1mcommit transaction[0m
Although the sql commands are executed and the records are deleted, I am unable to get the SQL commands generated.
I've tried using sqlite3 for testing and the
Could not log "sql.active_record" event.
error doesn't show up.
I've been trying to figure out where this logging error is coming from and I can't locate it. I'm not sure if I would just leave it alone since the commands are still executed.
This is a known issue with the driver that this being tracked here;
GitHub: GeneralLedger.find(params[:id]).delete throws error while logging the delete in ActiveRecord
To your point the Error is not preventing the action from being performed, it's just the output to the logs that is being omitted.
I'd expect further updates to be posted to the GitHub link above.

Error in an after hook, PG::InFailedSqlTransaction from Rspec

I was trying to run rspec from a model spec file, but I got this error: "An error occurred in an after hook"
"An error occurred in to after hook PG :: InFailedSqlTransaction:
ERROR: current transaction is aborted, commands ignored until end of
transaction. occurred at C :/ Ruby193/lib/.../postgresql_adapter: 294 "
I googled this issue, and I found a suggestion to downgrade my 'database_cleaner' to '1.0.1'. I did, but it doesn't work.
Does anyone have any idea how to solve this? Thanks in advance!
This can happen if you execute a bad SQL statement in the scope of a transaction, you rescue the exception from that statement, and then try and execute another SQL statement in the same transaction.
Once one statement in a transaction fails no more statements can be executed in that transaction.
Here's an example:
ActiveRecord::Base.transaction do
begin
ActiveRecord::Base.connection.execute "A bad query"
rescue => ex
puts ex.message
end
puts User.count
end
User.count raises PG::InFailedSqlTransaction because the previous SQL statement raised ActiveRecord::StatementInvalid and that was swallowed by the rescue.
So I would look for code that rescues in the scope of a transaction and then tries to run additional SQL statements.

Not nil code that works for both sqlite3 and pg

I have a rails app running sqlite3 in development and pg in production, currently running on Heroku. I am getting an error on my heroku app. I have a column called 'archived' which starts out as nil until the user pushes a button, then the current time gets written into the cell. Then all messages where archived != nil is then ordered by most recent.
Below is a portion of my heroku log:
2013-05-07T22:00:31.775149+00:00 app[web.1]: Completed 500 Internal Server Error in 34ms
2013-05-07T22:00:31.785541+00:00 app[web.1]:
2013-05-07T22:00:31.785541+00:00 app[web.1]: ActionView::Template::Error (PG::Error: ERROR: invalid input syntax for type timestamp: ""
2013-05-07T22:00:31.785541+00:00 app[web.1]: LINE 1: ... "messages".* FROM "messages" WHERE (archived <> '') ORDER ...
2013-05-07T22:00:31.785541+00:00 app[web.1]: ^
2013-05-07T22:00:31.785541+00:00 app[web.1]: : SELECT "messages".* FROM "messages" WHERE (archived <> '') ORDER BY archived desc LIMIT 10):
This tells me that the issue is this line of code from my controller:
#archived_messages = Message.where("archived <> ''").limit(10).order('archived desc')
What should I change this code to so that it works in both sqlite3 and pg?
Thanks in advance.
Got it!
#archived_messages = Message.where("archived IS NOT NULL").limit(10).order('archived desc')
source: Runs locally with SQLite, but on Heroku: PGError: ERROR: syntax error at or near "NULL"

Resources