Unable to create user model in Rspec - ruby-on-rails

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.

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

Spec Date Rails 4

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?

How to login with declarative_authorization in my rspec tests without going through the interface

At present, the following works when I call it from my Rspec tests:
def login_as(role)
#role = Role.create! :name => role
#virginia = User.create!(
:username => "Virginia",
:password => "password",
:password_confirmation => "password",
:email => "example#example.com")
#assignment = Assignment.create! user_id: #virginia.id, role_id: #role.id
visit login_path
fill_in "user_session_username", :with => #virginia.username
fill_in "user_session_password", :with => #virginia.password
click_on "submit_user_session"
end
Given that I've tested the interface already, I thought it might speed things up to not hit the interface hundreds of times just because many of my examples only make sense when a user has a role and is logged in. So, I tried this:
def login_as(role)
#role = Role.create! :name => role
#virginia = User.create!(
:username => "Virginia",
:password => "password",
:password_confirmation => "password",
:email => "example#example.com")
#assignment = Assignment.create! user_id: #virginia.id, role_id: #role.id
#user_session = UserSession.create! :username => #virginia.username, :password => #virginia.password
end
However, that version is not logging me in. Any thoughts?
To be clear, I'm not asking how to test declarative_authorization. I'm asking how to quickly login when I'm testing something else. For example, I use login_as(role) to test product#delete (an action only accessible to admins) like this:
login_as "admin"
visit product_path(#search)
click_link "delete_product"
page.current_path.should == products_path
page.should_not have_content "Retail Site Search"

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 3: Generate Fake Data to Populate DB

I am using faker to generate sample data. I have this as follows:
require 'faker'
namespace :db do
desc "Fill database with sample data"
task :populate => :environment do
Rake::Task['db:reset'].invoke
User.create!(:name => "rails",
:email => "example#railstutorial.org",
:password => "foobar",
:password_confirmation => "foobar")
99.times do |n|
#name = Faker::Name.name
name = "rails#{n+1}"
email = "example-#{n+1}#railstutorial.org"
password = "password"
user = User.create!(:name => name,
:email => email,
:password => password,
:password_confirmation => password)
end
end
end
The problem is that I have a couple of after_save callbacks that are not being called when the User is created. Why is that? Thanks
The methods:
after_save :create_profile
def create_profile
self.build_profile()
end
In all my reading, it seems that save! bypasses any custom before_save, on_save or after_save filters you have defined. The source code for create! reveals that it invokes save!. Unless you absolutely NEED the bang version, why are you using it? Try removing all your bang methods and just invoking the non-bang versions:
[1..100].each do |n|
name = "rails#{n+1}"
email = "example-#{n+1}#railstutorial.org"
password = "password"
user = User.new(:name => name, :email => email, :password => password, :password_confirmation => password)
if !user.save
puts "There was an error while making #{user.inspect}"
end
end

Resources