Ruby validation passes in console, fails in rake task - ruby-on-rails

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.

Related

Rails upgrade 3.2.* to 4 Does not show all user attributes in rails console

Kind of an odd bug I am running into. Working on upgrading a Rails app from 3.2.22.1 tp 4.2.11.3. Everything is working pretty well. Test suite is passing on green. However when I go into the rails console and do user = User.new or list the attributes using User.new.attributes I am only getting a few of the fields returned.
Specifically
{"_id"=>BSON::ObjectId('XXxxXXxxxxXXXxXX'),
"email"=>"",
"encrypted_password"=>"",
"sign_in_count"=>0,
"time_zone"=>"Central Time (US & Canada)",
"admin"=>false}
This list should be much larger, for example, it is excluding all Devise fields like last_sign_in_at or any of them. Here is what it looks like, the same command, run on our production server which is the previous version of rails
_id: xxxXXXxxxXXXXxXXXXxx,
invited_by_type: nil,
invited_by_field: nil,
invited_by_id: nil,
email: "",
encrypted_password: "",
reset_password_token: nil,
reset_password_sent_at: nil,
remember_created_at: nil,
sign_in_count: 0,
current_sign_in_at: nil,
last_sign_in_at: nil,
current_sign_in_ip: nil,
last_sign_in_ip: nil,
confirmation_token: nil,
confirmed_at: nil,
confirmation_sent_at: nil,
unconfirmed_email: nil,
invitation_token: nil,
invitation_created_at: nil,
invitation_sent_at: nil,
invitation_accepted_at: nil,
invitation_limit: nil,
name: nil,
time_zone: "Central Time (US & Canada)",
admin: false
I am worried that there is something failing silently and I am not detecting it. I can save the unlisted values in the console, but it does not show them to me, which is not how it worked previously.
Anyone understand why this is happening?
specific versions are:
mongid -> 5.0.1
devise -> 4.7.2
Rails -> 4.2.11.3
Latest version of Mongoid does not include attributes that were never written in attributes.
Unless you have references to documentation that claims that Mongoid would return attributes that were never written, you are experiencing expected behavior.

test error:-in Ruby on rails

I'm working with ruby on rails and I'm having a problem while running a "ruby -Itest test/models/user_test.rb". I get an error when I make changes in the regular expression /^[a-zA-Z0-9-]+$/ and now I am stuck in this problem and I don't know how to get over it.
My user.rb file:-
validates :profilename, presence: true,
uniqueness: true, format: { with: /^[a-zA-Z0-9-]+$/ , multiline: true,
message: 'Must be formatted correctly.' }
Running test:-
$ ruby -Itest test/models/user_test.rb
DL is deprecated, please use Fiddle
Run options: --seed 50723
Running:
.....#<ActiveModel::Errors:0x4ecc8a0 #base=#<User id: nil, first_name: "sarah", last_name: "gupta", profile_name: "S_arah-1", email: "sarah089#gma
il.com", encrypted_password: "", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at
: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: nil, updated_at: nil>, #messages={}>
E..
Finished in 0.380267s, 15.7784 runs/s, 28.9270 assertions/s..
1) Error: UserTest#test_a_user_can_have_a_correctly_formatted_profile_name: ArgumentError: wrong number of arguments (0 for 1..2) test/models/user_test.rb:41:in `block in <class:UserTest>'
6 runs, 11 assertions, 0 failures, 1 errors, 0 skips
Here is the code for a_user_can_have_a_correctly_formatted_profile_name
test "a user can have a correctly formatted profile name" do
user = User.new(first_name: 'sarah', last_name: 'gupta', email: 'sarah089#gmail.com')
user.password = user.password_confirmation = 'welcome'
user.profile_name = 's_arah-1'
assert.user.valid?
end
Thanks for your help!
It looks like the answer to your question is in the file user_test.rb. Try checking where test_a_user_can_have_a_correctly_formatted_profile_name is defined, and where it's called: according to the error, it's being called without the required one or two arguments. I'm guessing you need to give it a test username.

Rails to_json method: problems with unicode characters

I'm having troubles with unicode characters in my Rails app. The problem is that when I store the object with some string containing scandinavian characters, those characters then are not rendered correctly when using to_json method. Basically all those characters are rendered like this:
\"description\":\"\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\"
Here is example:
Item.create(:title => "Test title", :description => "With scandic characters öäöäö")
=> #<Item id: 198, title: "Test title", priority: nil, description: "With scandic characters öäöäö", bought_when: nil, warranty_until: nil, created_at: "2012-12-04 15:22:19", updated_at: "2012-12-04 15:22:19", user_id: nil, custom_id: nil, uuid: nil, position: 1, public: nil, secure_details: "", bookmark_id: nil, giveaway: nil, trash: false>
At this point the created object looks ok.
Item.last
returns
=> #<Item id: 198, title: "Test title", priority: nil, description: "With scandic characters \xC3\xB6\xC3\xA4\xC3\xB6\xC3\xA4\xC3\xB6", bought_when: nil, warranty_until: nil, created_at: "2012-12-04 15:22:19", updated_at: "2012-12-04 15:22:19", user_id: nil, custom_id: nil, uuid: nil, position: 1, public: nil, secure_details: "", bookmark_id: nil, giveaway: nil, trash: false>
This "With scandic characters \xC3\xB6\xC3\xA4\xC3\xB6\xC3\xA4\xC3\xB6" - does it still look ok? Or do I miss some proper encoding already at the item creation stage?
Anyway, now when call Item.last.to_json, I get this:
"description\":\"With scandic characters \\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\"
And at this point the string is definitely broken.
I'm lacking some knowledge about the proper characters encoding in Rails, so any hints would be appreciated. The item, however, looks fine when rendered in the browser - this happens only when doing a JSON response.
Ok, the issue was that MySQL db was not in unicode. This is fixed now by migrating to PosgreSQL, ensuring it is in unicode and using Taps gem to migrate the data. All according to this Railscast: http://railscasts.com/episodes/342-migrating-to-postgresql

Rspec new expectation syntax

I've the following rspec unit test:
require 'spec_helper'
describe Article do
describe ".recents" do
it "includes articles created less than one week ago" do
article = Article.create(created_at: Date.today - 1.week + 1.second)
expect(Article.recents).to eql([article])
end
it "excludes articles published at midnight one week ago" do
article = Article.create!(:created_at => Date.today - 1.week)
expect(Article.recents).to be_empty
end
end
end
and the Articlemodel:
class Article < ActiveRecord::Base
attr_accessible :description, :name, :price, :created_at
scope :recents, where('created_at <= ?', 1.week.ago)
end
when I run my tests I get:
1) Article.recents includes articles created less than one week ago
Failure/Error: expect(Article.recents).to eql([article])
expected: [#<Article id: 60, name: nil, description: nil, price: nil, created_at: "2012-11-14 00:00:01", updated_at: "2012-11-21 10:12:33", section_id: nil>]
got: [#<Article id: 60, name: nil, description: nil, price: nil, created_at: "2012-11-14 00:00:01", updated_at: "2012-11-21 10:12:33", section_id: nil>]
(compared using eql?)
Diff:#<ActiveRecord::Relation:0x007ff692bce158>.==([#<Article id: 60, name: nil, description: nil, price: nil, created_at: "2012-11-14 00:00:01", updated_at: "2012-11-21 10:12:33", section_id: nil>]) returned false even though the diff between #<ActiveRecord::Relation:0x007ff692bce158> and [#<Article id: 60, name: nil, description: nil, price: nil, created_at: "2012-11-14 00:00:01", updated_at: "2012-11-21 10:12:33", section_id: nil>] is empty. Check the implementation of #<ActiveRecord::Relation:0x007ff692bce158>.==.
# ./spec/models/article_spec.rb:7:in `block (3 levels) in <top (required)>'
Could someone please help me to figure out what's the error in my test?
It seems good for me.
You are comparing an activerecord relation (Article.recents) to an array ([article]), which is why the expectation is failing. (It looks like they are the same in the spec results because inspect converts the relation into an array before printing it out.)
Change your first expectation to this:
expect(Article.recents.to_a).to eql([article])

Rails: class' object_id changes after I make a request

I really can't explain this behavior, notice how after I make a request the class' object id has changed, and therefore my is_a? evaluation returns false.
any ideas? I'm not even sure how to debug this. Also, this isn't related to making a request from the command line. The same behavior is exhibited on the web server as well, it's just easier to explain from the command line.
staging$ RAILS_ENV=staging script/console
Loading staging environment (Rails 2.3.2)
>> c = CartItem.new
=> #<CartItem id: nil, order_id: nil, order_source: nil, date: nil, user_id: nil, created_at: nil, updated_at: nil, paid: nil, payment_id: nil, values: nil, cart_description: nil, type: nil, price: nil, email: nil, error: nil>
>> c.class.object_id
=> 70151495336400
>> CartItem.object_id
=> 70151495336400
>> c.is_a? CartItem
=> true
>> app = ActionController::Integration::Session.new
=> #<ActionController::Integration::Session:0x7f9ad5c55db0 .... >
>> app.get("site/favorite")
=> 200
>> c.class.object_id
=> 70151495336400
>> CartItem.object_id
=> 70151496019760
>> c.is_a? CartItem
=> false
>> c.class
=> CartItem(id: integer, order_id: string, order_source: string, date: date, user_id: integer, created_at: datetime, updated_at: datetime, paid: boolean, payment_id: integer, values: text, cart_description: string, type: string, price: integer, email: string, error: string)
Every new context (request/response cycle) will regenerate the object IDs. You may want to use responds_to?, instead of is_a?.
Since the ActionController::Integration module is used for integration testing, getting a url reloads your classes, therefore redefining the CartItem identifier. You now basically have two CartItem classes, one hanging around on your stack without an identifier pointing to it anymore (the "old one") and one referenced by the CartItem identifier.

Resources