Spec Date Rails 4 - ruby-on-rails

I want to add a birthday date to my user model, this is how I implemented it:
user.rb
validates_date :birthday_date
user_spec.rb
describe User do
before(:each) do
#attr = {
:birthday_date => Date.new(1992, 8, 27),
:nom => "Utilisateur",
:email => "user#example.com",
:password => "foobar",
:password_confirmation => "foobar"
}
end
it "..." do
User.create!(#attr)
end
it "must have a correct date" do
bad_guy = User.new(#attr.merge(:birthday_date => ""))
bad_guy.should_not be_valid
end
But when I want to test it, I have got this error :
Failure/Error: #follower = Factory(:user)
ActiveRecord::RecordInvalid:
Validation failed: Birthday date is not a valid date
Why is my date not accepted?

Related

Rails Sample_App, Test errors

So following the Hartl sample app tutorials, and having a bit of trouble getting some tests to past regarding the relationship spec.
in my spec file I have
describe "follow methods" do
before(:each) do
#follower = User.create!( :name => "Example User",
:email => "user#example.com",
:password => "foobar",
:password_confirmation => "foobar"
)
#followed = User.create!( :name => "Example User",
:email => "user_five#example.com",
:password => "foobar",
:password_confirmation => "foobar"
)
#attr = { :followed_id => #followed.id }
#relationship = #follower.relationships.create!(#attr)
end
I know it's not the same as in the book however I'm not using FactoryGirl.
When using this block for tests I am getting an error with my #attr which reads;
Failure/Error: #attr = { :followed_id => #followed.id }
NoMethodError:
undefined method `id' for #<Hash:0x00000108d0b2a0>
However, when I run this block in my console it works just fine. The id is set according to the #attr, and I can call .id on #followed.
Any help would be much appreciated as always!
According to your error, the method id does not exist for a Hash.
To access that, you can use this:
#attr = { :followed_id => #followed['id'] }
The problem was you were trying to do #followed.id

Why is Rspec insisting that the password attribute is blank, when it is not?

I'm writing a user model and RSpec is insisting I left fields blank that are, in fact, populated with a perfectly valid password. Here is my spec/models/user_spec.rb file:
require 'spec_helper'
describe User do
before(:each) do
#attr = {
:name => "Example User",
:email => "user#example.com",
:password => "password",
:password_confirmation => "password"
}
end
it "should create a new instance given valid attributes" do
User.create!(#attr)
end
it "should require a name" do
no_name_user = User.new(#attr.merge(:name => ""))
no_name_user.should_not be_valid
end
it "should reject names that are too long" do
long_name = "a" * 51
long_name_user = User.new(#attr.merge(:name => long_name))
long_name_user.should_not be_valid
end
it "should accept valid email addresses" do
addresses = %w[user#foo.com THE_USER#foo.bar.org first.last#foo.jp]
addresses.each do |address|
valid_email_user = User.new(#attr.merge(:email => address))
valid_email_user.should be_valid
end
end
it "should reject invalid email addresses" do
addresses = %w[user#foo,com user_at_foo.org example.user#foo.]
addresses.each do |address|
invalid_email_user = User.new(#attr.merge(:email => address))
invalid_email_user.should_not be_valid
end
end
it "should reject duplicate email addresses" do
User.create!(#attr)
user_with_duplicate_email = User.new(#attr)
user_with_duplicate_email.should_not be_valid
end
it "should reject email addresses identical up to case" do
upcased_email = #attr[:email].upcase
User.create!(#attr.merge(:email => upcased_email))
user_with_duplicate_email = User.new(#attr)
user_with_duplicate_email.should_not be_valid
end
describe "password validations" do
it "should require a password" do
User.new(#attr.merge(:password => "", :password_confirmation => "")).should_not be_valid
end
it "should require a matching password confirmation" do
User.new(#attr.merge(:password_confirmation => "invalid")).should_not be_valid
end
it "should reject short passwords" do
short = "a" * 5
hash = #attr.merge(:password => short, :password_confirmation => short)
User.new(hash).should_not be_valid
end
it "should reject long passwords" do
long = "a" * 41
hash = #attr.merge(:password => long, :password_confirmation => long)
User.new(hash).should_not be_valid
end
end
describe "password encryption" do
before(:each) do
#user = User.create!(#attr.merge(:password => "foobar", :password_confirmation => "foobar"))
end
it "should have an encrypted password attribute" do
#user.should respond_to(:encrypted_password)
end
end
end
Here is my app/models/user.rb file:
class User < ActiveRecord::Base
attr_accessible :name, :email
attr_accessor :password
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates(:name, :presence => true,
:length => { :maximum => 50 })
validates(:email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false })
validates(:password, :presence => true,
:confirmation => true,
:length => { :within => 5..41 })
end
After running RSpec, I receive the following errors:
1) User should create a new instance given valid attributes
Failure/Error: User.create!(#attr)
ActiveRecord::RecordInvalid:
Validation failed: Password can't be blank
# ./spec/models/user_spec.rb:25:in `block (2 levels) in <top (required)>'
2) User should accept valid email addresses
Failure/Error: valid_email_user.should be_valid
expected #<User id: nil, name: "Example User", email: "user#foo.com", created_at: nil, updated_at: nil, encrypted_password: nil> to be valid, but got errors: Password can't be blank
# ./spec/models/user_spec.rb:43:in `block (3 levels) in <top (required)>'
# ./spec/models/user_spec.rb:41:in `each'
# ./spec/models/user_spec.rb:41:in `block (2 levels) in <top (required)>'
3) User should reject duplicate email addresses
Failure/Error: User.create!(#attr)
ActiveRecord::RecordInvalid:
Validation failed: Password can't be blank
# ./spec/models/user_spec.rb:56:in `block (2 levels) in <top (required)>'
4) User should reject email addresses identical up to case
Failure/Error: User.create!(#attr.merge(:email => upcased_email))
ActiveRecord::RecordInvalid:
Validation failed: Password can't be blank
# ./spec/models/user_spec.rb:63:in `block (2 levels) in <top (required)>'
5) User password encryption should have an encrypted password attribute
Failure/Error: #user = User.create!(#attr.merge(:password => "foobar", :password_confirmation => "foobar"))
ActiveRecord::RecordInvalid:
Validation failed: Password can't be blank
# ./spec/models/user_spec.rb:92:in `block (3 levels) in <top (required)>'
The problem with every one of these is that the password field is not blank! It is populated with the word "password" - which falls well between the limits of 5 and 41. On some occasions I've merged it into the attributes of that very specific test.
Can anybody please explain why these tests are failing?
I don't know the exact issue, but I can teach you how to debug it.
Step 1: Open up a Rails console in the test environment.
$> rails console test
This allows you to execute code as if it were in a test spec. I am not sure if you are familiar with environments, but here is a good article anyway.
Step 2: Pick the easiest failure to fix. In this case, it appears to be User should create a new instance given valid attributes.
Step 3: Type in all the code you expect to be executed for the failing spec, line by line, into the test console.
>> #attr = {
:name => "Example User",
:email => "user#example.com",
:password => "password",
:password_confirmation => "password"
}
>> User.create!(#attr)
Step 4: If you are unable to reproduce the failure, something else is wrong with your setup. Look inside spec_helper.rb. Maybe you forgot to run rake db:migrate or rake db:test:prepare? This becomes more important as you use more advanced tools like Zeus. Fix it.
Step 5: If you are able to reproduce the failure, yeah! Carefully inspect the error messages that are printed. As #AmitKumarGupta mentioned, it could be because password is not mass-assignable. Here is a good article on what that means. Try various ways of creating the user. For example,
>> user = User.new #attr
>> user.valid? # should return true, but if it is false ...
>> user.errors # is there an error for password and password confirmable?
>> user.inspect # maybe some rouge code deleted the password by accident?
Step 6: Hopefully by now you have found the solution. Add the solution and rerun the specs. Now repeat from Step 1 until it all passes.
Side Note
I strongly recommend FactoryGirl and Shoulda. Here is a gist for should have_a_valid_factory.
Update
If you followed my instructions above and executed the following
>> u = User.new #attr
You will see the following error message:
WARNING: Can't mass-assign protected attributes for User: password, password_confirmation
The article I linked above will explain what this means. Using FactoryGirl will fix your issue, or you can use
user = User.new #attr # without password, password confirmation
user.password = 'password'
user.password_confirmation = 'password'
user.save!

Rails and Rspec - can't mass-assign protected attributes

I am creating a Rails application with TDD using rspec. I am getting an error I can't remove :
Failure/Error: invalid_user = User.new(#attr.merge("provider" => ""))
ActiveModel::MassAssignmentSecurity::Error:
Can't mass-assign protected attributes: uid, info
Here is my user spec :
user_spec.rb
require 'spec_helper'
describe User do
before(:each) do
#attr = {"provider" => "providerexample", "uid" => "uidexample", "info" => {"name" => "Example"}}
end
it "should create a new instance given valid attributes" do
user = User.create_with_omniauth(#attr)
end
it "should require a provider" do
invalid_user = User.new(#attr.merge("provider" => ""))
invalid_user.should_not be_valid
end
it "should require a uid" do
invalid_user = User.new(#attr.merge("uid" => ""))
invalid_user.should_not be_valid
end
end
And my user.rb
class User < ActiveRecord::Base
attr_accessible :name, :credits, :email, :provider
validates :name, :provider, :uid, :presence => true
def self.create_with_omniauth(auth)
create! do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.name = auth["info"]["name"]
end
end
end
If I debug the mass-assign error by adding uid and info to the attr_accessible, I still get the following error unknown attribute: info.
If you merge what you had as #attr with info, then it'll exist for the create_with_omniauth call, but not the regular create methods.
describe User do
let(:user_attributes) { {"provider" => "providerexample", "uid" => "uidexample"} }
it "should create a new instance given valid attributes" do
expect {
User.create_with_omniauth(user_attributes.merge({"info" => {"name" => "example"}))
}.to not_raise_error
end
end

Unable to create user model in Rspec

When I run the following spec:
require 'spec_helper'
describe User do
before :each do
#user = User.new :email => "foo#bar.com", :password => "foobar", :password_confirmation => "foobar"
end
it "should be valid" do
#user.should be_valid
end
end
I get this error:
1) User should be valid
Failure/Error: #user = User.new :email => "foo#bar.com", :password => "foobar", :password_confirmation => "foobar"
ActiveRecord::UnknownAttributeError:
unknown attribute: email
# ./spec/models/user_spec.rb:5:in `new'
However, when I go in to console and run
user = User.new :email => "foo#bar.com", :password => "foobar", :password_confirmation => "foobar"
user.valid?
It returns true. For some reason, in my test, I am unable to create a User instance, saying that the email attribute is inaccessible.
Console uses the development database, but specs use the test database. Make sure email is defined in both.

RoR tutorial, chapter 7 - rspec tests failing: NoMethodError 'encrypt'

Well I've searched all over the place and it seems that nobody else has the issue with this 'encrypt' method causing their tests to fail, though it seems plenty others have had some difficulty with chapter 7. Without further adieu,
Here's the link to Hartl's Chapter 7
My code in the user model file, and the corresponding spec file, appear to be completely exact to what he has written and I still cannot get the tests to pass. The errors?
Failures:
1) User should create a new instance given valid attributes
Failure/Error: User.Create!(#attr)
NoMethodError: undefined method 'encrypt' for #<User:asdf>
#./app/models/user.rb:22:in 'has_password?'
#./app/models/user.rb:28:in 'encrypt_password'
#./spec/models/user_spec.rb:15:in 'block (2 levels) in <top (required)>'
2) User should not allow duplicate email addresses
Failure/Error: User.Create!(#attr)
NoMethodError: undefined method 'encrypt' for #<User:asdf>
#./app/models/user.rb:22:in 'has_password?'
#./app/models/user.rb:28:in 'encrypt_password'
#./spec/models/user_spec.rb:15:in 'block (2 levels) in <top (required)>'
3) User should reject email addresses identical up to case
Failure/Error: User.Create!(#attr)
NoMethodError: undefined method 'encrypt' for #<User:asdf>
#./app/models/user.rb:22:in 'has_password?'
#./app/models/user.rb:28:in 'encrypt_password'
#./spec/models/user_spec.rb:15:in 'block (2 levels) in <top (required)>'
...
7) User has_password? method should be false if passwords do not match
Failure/Error: User.Create!(#attr)
NoMethodError: undefined method 'encrypt' for #<User:asdf>
#./app/models/user.rb:22:in 'has_password?'
#./app/models/user.rb:28:in 'encrypt_password'
#./spec/models/user_spec.rb:15:in 'block (3 levels) in <top (required)>'
so i'm getting the same error messages for each test and I am going nuts trying to find out why!
Here's my user.rb:
require 'digest'
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
#automatically create the virtual attribute for 'password_confirmation'
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
before_save :encrypt_password
#returns true if the users password matches the submitted one
def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end
private
def encrypt_password
self.salt = make_salt unless has_password?(password)
self.encrypted_password = encrypt(password)
end
def encrypt_string
secure_hash("#{salt}--#{string}")
end
def make_salt
secure_hash("#{Time.now.utc}--#{password}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
end
and my user_spec.rb file:
require 'spec_helper'
require 'digest'
describe User do
before(:each) do
#attr = {
:name => "User Name",
:email => "example#email.com",
:password => "password",
:password_confirmation => "password"
}
end
it "should create a new instance given valid attributes" do
User.create!(#attr)
end
it "should require a name" do
no_name_user = User.new(#attr.merge(:name => ""))
no_name_user.should_not be_valid
end
it "should require an email" do
no_email_user = User.new(#attr.merge(:email => ""))
no_email_user.should_not be_valid
end
it "should reject names that are too long" do
long_name = "a" * 51
long_name_user = User.new(#attr.merge(:name => long_name))
long_name_user.should_not be_valid
end
it "should accept valid email addresses" do
addresses = %w[user#foo.com THE_USER#foo.bar.org first.last#foo.jp]
addresses.each do |address|
valid_email_user = User.new(#attr.merge(:email => address))
valid_email_user.should be_valid
end
end
it "should reject invalid email addresses" do
addresses = %w[user#foo,com user_at_foo.org example.user#foo.]
addresses.each do |address|
invalid_email_user = User.new(#attr.merge(:email => address))
invalid_email_user.should_not be_valid
end
end
it "should not allow duplicate email addresses" do
User.create!(#attr)
user_with_duplicate_email = User.new(#attr)
user_with_duplicate_email.should_not be_valid
end
it "should reject email addresses identical up to case" do
upcased_email = #attr[:email].upcase
User.create!(#attr.merge(:email => upcased_email))
user_with_duplicate_email = User.new(#attr)
user_with_duplicate_email.should_not be_valid
end
describe "password validations" do
it "should require a password" do
User.new(#attr.merge(:password => "", :password_confirmation => ""))
should_not be_valid
end
it "should require password to match the password confirmation" do
User.new(#attr.merge(:password_confirmation => "invalid"))
should_not be_valid
end
it "should reject short passwords" do
short = "a" * 5
hash = #attr.merge(:password => short, :password_confirmation => short)
User.new(hash).should_not be_valid
end
it "should reject long passwords" do
long = "a" * 41
hash = #attr.merge(:password => long, :password_confirmation => long)
User.new(hash).should_not be_valid
end
end
describe "password encryption" do
before(:each) do
#user = User.create!(#attr)
end
it "should have an encrypted password attribute" do
#user.should respond_to(:encrypted_password)
end
it "should not allow a blank encrypted password" do
#user.encrypted_password.should_not be_blank
end
end
describe "has_password? method" do
before(:each) do
#attr = User.create!(#attr)
end
it "should be true if the passwords match" do
#user.has_password?(#attr[:password]).should be_true
end
it "should be false if the passwords don't match" do
#user.has_password?("invalid").should be_false
end
end
end
Any help would be greatly appreciated. I've poured over other's problems, my code, and changed various aspects to try and get the tests to work, all to no avail. I hope it's not something really stupid I'm still not seeing.
Your error is here:
def encrypt_string
secure_hash("#{salt}--#{string}")
end
You are calling encrypt in the following encrypt_password method but your method above is named encrypt_string:
def encrypt_password
self.salt = make_salt unless has_password?(password)
self.encrypted_password = encrypt(password)
end
Just change encrypt_string to encrypt in the method definition and you should be good to go.

Resources