rspec not saving to database - ruby-on-rails

I'm trying to test the login method below, but it does not seem to be saving the data_provider_user to the database. I've checked using debugger and it works perfectly until it leaves the method and goes back to the rspec code, as shown below. I've also checked to see if the object is valid after it save using .valid? and it is so I'm a bit lost!
def login
require 'TwitterOauth'
#data_provider_user = DataProviderUser.find(params[:id])
if #data_provider_user.twitter?
#request_token = TwitterOauth.request_url
#data_provider_user.access_token = #request_token.token
#data_provider_user.oauth_token_secret = #request_token.secret
if #data_provider_user.save
debugger
redirect_to #request_token.authorize_url
end
end
end
Test:
it "should update the tokens" do
require 'TwitterOauth'
TwitterOauth.stub(:request_url).and_return(#token)
debugger
get :login, {id: #data_provider_user.id}
debugger
#data_provider_user.access_token.should_not eq(nil)
#data_provider_user.oauth_token_secret.should_not eq(nil)
end
Debugger output:
#<DataProviderUser id: 84, user_id: 63, data_provider_id: 63, username: nil, password: nil, created_at: "2013-02-19 15:21:59", updated_at: "2013-02-19 15:21:59", access_token: nil, update_frequency: nil, oauth_token_secret: nil>
#<DataProviderUser id: 84, user_id: 63, data_provider_id: 63, username: nil, password: nil, created_at: "2013-02-19 15:21:59", updated_at: "2013-02-19 15:22:12", access_token: "186553918-sEAEO2fcvtyO1x99eH4Q4XwVcOYatODCQ5f1TwqD", update_frequency: nil, oauth_token_secret: "gLw2PtUyTZfxIan1gJBnbP7icboXbi98KlUoOn7ycVs">
#<DataProviderUser id: 84, user_id: 63, data_provider_id: 63, username: nil, password: nil, created_at: "2013-02-19 15:21:59", updated_at: "2013-02-19 15:21:59", access_token: nil, update_frequency: nil, oauth_token_secret: nil>
Any help would be greatly appreciated!!
------ UPDATE -------
There was actually nothing wrong with the code, the issue was that rspec was not reloading it in time. A way to get around this was to use:
#data_provider_user.reload
before hand which refreshes the object, updating the values accordingly.

There was actually nothing wrong with the code, the issue was that rspec was not reloading it in time. A way to get around this was to use:
#data_provider_user.reload
before hand which refreshes the object, updating the values accordingly.

In spec/rails_helper.rb
Set false to use_transactional_fixtures:
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = false

Are you sure you're looking at the right database? When you're doing testing it's probably going to myapp_test (myapp being whatever you called your app). You may be looking at your myapp_development database.
If you're accessing the database via rails db chances are you're going into your development database. You can check with select database(); if you're using MySQL. If you want to check your test database, then use RAILS_ENV=test rails db. Again, you can use the select statement to verify you're in the right database.

Related

Rails console output to recreate objects

I accidentally deleted 1000 objects from a database and now trying to recreate these objects. Thankfully I was able to scroll through my console output and find the records. I copy and pasted the console output which is in this (greatly shortened) format:
[#<Assignment id: 276503, school_id: 2091, listing_id: 251572, created_at: "2018-08-30 05:02:36", updated_at: "2018-08-30 05:02:36">, #<Assignment id: 279532, school_id: 1233, listing_id: 252702, created_at: "2018-08-30 06:19:12", updated_at: "2018-08-30 06:19:12">]
#...
I can't get the console to assign this output to a variable so I can figure out how to use this data to recreate the objects in the db:
irb(main):040:0> a = [#<Assignment id: 276503, school_id: 2091, listing_id: 251572, created_at: "2018-08-30 05:02:36", updated_at: "2018-08-30 05:02:36">, #<Assignment id: 279532, school_id: 1233, listing_id: 252702, created_at: "2018-08-30 06:19:12", updated_at: "2018-08-30 06:19:12">]
irb(main):041:1*
Does anyone have ideas how to turn this console output back into objects in my db?
If you have the problems with assigning a huge array to a variable in the console, you can try to use rake task.
array.each do |e|
options = e.split(',')
school_id = options.detect{|i| i.match?(/school_id/)}.split(':').last
listing_id = options.detect{|i| i.match?(/listing_id/)}.split(':').last
Assignment.create(school_id: school_id, listing_id: listing.id)
end
This should work. It is quite consuming, but from another perspective easy and fast.
I would paste that output on sublime or any other text editor and then format
to become something useful...
A bunch of inserts using SQL or just .create() that i would then paste it on the console

Testing that Devise is re-sending confirmation instructions email in a background worker

I want to send Devise confirmation instructions to users a second time if they haven't confirmed within two days of signing up, however I can't seem to get my success case test to pass.
Background worker (runs once a day):
class ResendConfirmationWorker
include Sidekiq::Worker
sidekiq_options queue: :resend_confirmation, retry: false
def perform
d = Time.zone.now - 2.days
users = User.where.not(confirmation_sent_at: nil)
.where(confirmed_at: nil)
.where(created_at: d.beginning_of_day..d.end_of_day)
users.find_each do |user|
user.send_confirmation_instructions
end
end
end
RSpec test:
require 'rails_helper'
describe ResendConfirmationWorker, type: :job do
before do
time = Time.zone.now - 2.days
#user = create :unconfirmed_user,
created_at: time,
confirmation_sent_at: time
end
def run_job
subject.perform
end
it 'resends a confirmation email to people who haven’t accepted it within two days' do
run_job
expect(Devise::Mailer.deliveries.count).to eq 1
end
end
I always get 0 instead of 1. I've also tried looking at Sidekiq::Extensions::DelayedMailer.jobs.size and Devise.mailer.deliveries.count but they also return 0.
Lastly, I put a binding in the worker and run user.send_confirmation_instructions manually:
[1] pry(#<ResendConfirmationWorker>)> user.send_confirmation_instructions
=> #<ActionMailer::DeliveryJob:0x007fc53f05c420
#arguments=
["Devise::Mailer",
"confirmation_instructions",
"deliver_now",
#<User id: 1, email: "unconfirmed1#example.com", created_at: "2017-01-05 04:40:13", updated_at: "2017-01-07 04:40:13", company_id: nil, name: "Unconfirmed User", invitation_token: nil, invitation_created_at: nil, invitation_sent_at: nil, invitation_accepted_at: nil, invitation_limit: nil, invited_by_type: nil, invited_by_id: nil, invitations_count: 0>,
"token1",
{}],
#job_id="9b5f6231-3194-4c57-9a6b-a38368cec603",
#priority=nil,
#queue_name="mailers">
It looks like it's correctly adding a new confirmation instructions email to the mailer queue, so why can't I see it from my test?

Ruby validation passes in console, fails in rake task

This is my EmailContact model:
class EmailContact < ActiveRecord::Base
validates :email, :presence => true, :email => true
end
I am using the ruby gem valid_email.
I run the following in my rails console, in the same environment as my rake task I will show later:
>> email_contact = EmailContact.new(:email => 'a253545#gmail.com')
>> email_contact.valid?
true
So, as you can see, in the rails console I am building an EmailContact and it is valid.
Then I run this in my rake task:
list_entity = {:branch=>"Nashua Branch-YMCA of Greater Nashua", :branch_id=>"485", :call_type=>nil, :client_id=>"2264", :client_name=>"YMCA of Greater Nashua", :date_of_birth=>nil, :email=>"a253545#gmail.com", :first_name=>"Sridhar", :last_name=>"Tipirneni", :list_entity_id=>"277795", :mem_id=>"4085008", :mem_unit_id=>"2138728", :member_id=>"0213262-01", :membership_type=>"Dual 2 Adult Family", :membership_type_id=>"5203", :most_recent_join_date=>nil, :old_membership_type=>nil, :phone_number=>"(970)456-1010", :primary_language=>"English", :termination_date=>nil, :termination_reason=>nil, :unit_id=>"0213262", :unit_type=>nil, :visits=>nil, :"#i:type"=>"c:NpsListEntityDto"}
email_contact = EmailContact.new(list_entity.except(:"#i:type"))
puts email_contact.valid?
This returns false. The only validation, at all, is the email. Why does this email validate successfully in my console but fail in my rake task?
FYI, when I remove :email => true from my EmailContact model and only validate the presence of an :email, they both work fine. So the issue is definitely within the :email => true piece of my validation, but I don't understand why it passes in one place and fails in another.
EDIT
In my console, my model looks like this when using the full list_entity:
#<EmailContact id: nil, branch: "Nashua Branch-YMCA of Greater Nashua", branch_id: 485, call_type: nil, client_id: 2264, client_name: "YMCA of Greater Nashua", date_of_birth: nil, email: "a253545#gmail.com", first_name: "Sridhar", last_name: "Tipirneni", list_entity_id: 277795, mem_id: "4085008", mem_unit_id: "2138728", member_id: "0213262-01", membership_type: "Dual 2 Adult Family", membership_type_id: 5203, most_recent_join_date: nil, old_membership_type: nil, phone_number: "(970)456-1010", primary_language: "English", termination_date: nil, termination_reason: nil, unit_id: "0213262", visits: nil, loaded_at: nil, failed_at: nil, unit_type: nil, created_at: nil, updated_at: nil, list_id: nil>
In my rake task, when I run email_contact.inspect, this is returned:
#<EmailContact id: nil, branch: "Nashua Branch-YMCA of Greater Nashua", branch_id: 485, call_type: nil, client_id: 2264, client_name: "YMCA of Greater Nashua", date_of_birth: nil, email: "a253545#gmail.com", first_name: "Sridhar", last_name: "Tipirneni", list_entity_id: 277795, mem_id: "4085008", mem_unit_id: "2138728", member_id: "0213262-01", membership_type: "Dual 2 Adult Family", membership_type_id: 5203, most_recent_join_date: nil, old_membership_type: nil, phone_number: "(970)456-1010", primary_language: "English", termination_date: nil, termination_reason: nil, unit_id: "0213262", visits: nil, loaded_at: nil, failed_at: nil, unit_type: nil, created_at: nil, updated_at: nil, list_id: nil>
As you can see, they are both the exact same - The console model is valid, the rake model is invalid.
EDIT 2
I am using the valid_email gem, mentioned above. Here is the filepath:
/Users/luigi/.rvm/gems/ruby-2.0.0-p247#hub/gems/valid_email-0.0.4/lib/valid_email/email_validator.rb
All of my other gems are stored here as well it seems like.
It may also be worth mentioning that I get this warning before the validation fails:
[deprecated] I18n.enforce_available_locales will default to true in
the future. If you really want to skip validation of your locale you
can set I18n.enforce_available_locales = false to avoid this message.
20 hours later, I found the issue.
Using savon, all of the strings returned in my hash were being converted to a datatype of Nori::StringWithAttributes. The encoding was the same (UTF-8), but the class was different.
Running email_contact.email = email_contact.email.to_s prior to checking if the model is valid solves the issue.

Rails 3.0.9 Model attributes are lost on database query

If i open the console and type in the following code, my model looses attributes. In all cases only the first attribute after the id is accessable. I had this problem on one server. My old server is working fine with the same code and same versions. Here the output:
irb(main):001:0> User.new
=> #<User id: nil, encrypted_uid: nil, encrypted_access_token: nil, created_at: nil, updated_at: nil>
irb(main):002:0> User.first
=> #<User id: 1, encrypted_uid: "I7lPHOYoGMNWki3cZtb5oA==\n">
ActiveModel::MissingAttributeError (missing attribute: encrypted_access_token):
Has anyone an idea to get it working? Thanks in advance.
I had to recreate the application and copy the model into hte new application. after that everything worked fine. No clue what was wrong.

Troubleshooting 'Unknown record property / related component "user" on "sfGuardUserProfile"' when loading fixture data

I am some trouble loading fixture data, that I have added manually in my admin backend and then simply exported the data using 'symfony doctrine:data-dump'
schema.yml
http://pastebin.com/5LTzNtU1
fixtures.yml (snippet)
http://pastebin.com/CNWyhrgc
Now everything works fine when I run symfony doctrine:build --all, but when i try to load the data, I get:
Unknown record property / related component "user" on "sfGuardUserProfile"
This is really odd, as I have saved users and they've gone into both tables fine, just not when loading the fixtures that I exported fomr the database.
Does anyone have any ideas what the problem could be?
Thanks
Try this. create users.yml with
sfGuardUser:
sfGuardUser_1:
email_address: test#example.com
username: test_user
algorithm: sha1
salt: 6fdcd99a2c73d6270f1ed8dbbf7ccd3e
password: fed98ad16c318197d16a2d7375f81e1afbce0792
is_active: true
is_super_admin: true
last_login: '2011-05-03 09:37:08'
first_name: ''
last_name: ''
created_at: '2011-04-11 11:29:02'
updated_at: '2011-05-03 09:37:08'
and profile.yml with
sfGuardUserProfile:
sfGuardUserProfile_1:
User: sfGuardUser_1
email_new: test#example.com
firstname: Test
lastname: User
validate_at: null
validate: null
created_at: '2011-04-19 15:46:16'
updated_at: '2011-04-19 15:49:14'
Maybe it help you.

Resources