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

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.

Related

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!

FactoryGirl issues - `factory': wrong number of arguments (0 for 1) (ArgumentError)

I am working through the Ruby on Rails tutorial and I am so close to the end, but Factory Girl is not making it easy for me.
I can't run any of the spec files that call for factory.
require 'spec_helper'
require 'factory_girl_rails'
describe User do
before(:each) do
#attr = { :name => "Example User",
:email => "user#example.com",
:password => "foobar",
:password_confirmation => "foobar"
}
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 address" 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 reject duplicate email addresses" do
#put user with given email address into the database
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 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 set the encrypted password" do
#user.encrypted_password.should_not be_blank
end
it "should be true if 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
describe "authenticate method" do
it "should return nil on email/password mismatch" do
wrong_password_user = User.authenticate(#attr[:email], "wrongpass")
wrong_password_user.should be_nil
end
it "should return nil for an email address with no user" do
nonexistent_user = User.authenticate("bar#foo.com", #attr[:password])
nonexistent_user_should be_nil
end
it "should return the user on email/password match" do
matching_user = User.authenticate(#attr[:email], #attr[:password])
matching_user.should == #user
end
end
end
describe "admin attribute" do
before(:each) do
#user = User.create!(#attr)
end
it "should respond to admin" do
#user.should respond_to(:admin)
end
it "should not be an admin by default" do
#user.should_not be_admin
end
it "should be convertible to an admin" do
#user.toggle!(:admin)
#user.should be_admin
end
end
describe "micropost associations" do
before(:each) do
#user = User.create{#attr}
#mp1 = FactoryGirl.create(:micropost, :user => #user, :created_at => 1.day.ago)
#mp2 = FactoryGirl.create(:micropost, :user => #user, :created_at => 1.hour.ago)
end
it "should have a microposts attribute" do
#user.should respond_to(:microposts)
end
it "should have the right microposts in the right order" do
#user.microposts.should == [#mp2, #mp1]
end
it "should destroy associated microposts" do
#user.destroy
[#mp1, #mp2].each do |micropost|
Micropost.find_by_id(micropost.id).should be_nil
end
end
end
end
factories.rb
#by using the symbol ':user', we get Factory Girl to simmulate the User model
require 'spec_helper'
FactoryGirl.define do
factory :user do |user|
user.name "User Name"
user.email "user#ex.com"
user.password "foobar"
user.password_confirmation "foobar"
end
factory.sequence :email do |n|
"person-#{n}#example.com"
end
factory :micropost do |micropost|
micropost.content "Foo bar"
micropost.association :user
end
end
This is the error message I get:
/Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/factory_girl-4.1.0/lib/factory_girl/syntax/default.rb:15:in `factory': wrong number of arguments (0 for 1) (ArgumentError)
from /Users/samanthacabral/rails_projects/sample/spec/factories.rb:13:in `block in <top (required)>'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/factory_girl-4.1.0/lib/factory_girl/syntax/default.rb:49:in `instance_eval'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/factory_girl-4.1.0/lib/factory_girl/syntax/default.rb:49:in `run'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/factory_girl-4.1.0/lib/factory_girl/syntax/default.rb:7:in `define'
from /Users/samanthacabral/rails_projects/sample/spec/factories.rb:4:in `<top (required)>'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:245:in `load'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:245:in `block in load'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:236:in `load_dependency'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:245:in `load'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/factory_girl-4.1.0/lib/factory_girl/find_definitions.rb:16:in `block in find_definitions'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/factory_girl-4.1.0/lib/factory_girl/find_definitions.rb:15:in `each'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/factory_girl-4.1.0/lib/factory_girl/find_definitions.rb:15:in `find_definitions'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/factory_girl_rails-4.1.0/lib/factory_girl_rails/railtie.rb:26:in `block in <class:Railtie>'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/activesupport-3.2.8/lib/active_support/lazy_load_hooks.rb:34:in `call'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/activesupport-3.2.8/lib/active_support/lazy_load_hooks.rb:34:in `execute_hook'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/activesupport-3.2.8/lib/active_support/lazy_load_hooks.rb:43:in `block in run_load_hooks'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/activesupport-3.2.8/lib/active_support/lazy_load_hooks.rb:42:in `each'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/activesupport-3.2.8/lib/active_support/lazy_load_hooks.rb:42:in `run_load_hooks'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/railties-3.2.8/lib/rails/application/finisher.rb:59:in `block in <module:Finisher>'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/railties-3.2.8/lib/rails/initializable.rb:30:in `instance_exec'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/railties-3.2.8/lib/rails/initializable.rb:30:in `run'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/railties-3.2.8/lib/rails/initializable.rb:55:in `block in run_initializers'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/railties-3.2.8/lib/rails/initializable.rb:54:in `each'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/railties-3.2.8/lib/rails/initializable.rb:54:in `run_initializers'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/railties-3.2.8/lib/rails/application.rb:136:in `initialize!'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/railties-3.2.8/lib/rails/railtie/configurable.rb:30:in `method_missing'
from /Users/samanthacabral/rails_projects/sample/config/environment.rb:5:in `<top (required)>'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `block in require'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:236:in `load_dependency'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require'
from /Users/samanthacabral/rails_projects/sample/spec/spec_helper.rb:81:in `<top (required)>'
from /Users/samanthacabral/rails_projects/sample/spec/models/user_spec.rb:12:in `require'
from /Users/samanthacabral/rails_projects/sample/spec/models/user_spec.rb:12:in `<top (required)>'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `load'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `block in load_spec_files'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `map'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `load_spec_files'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/rspec-core-2.11.1/lib/rspec/core/command_line.rb:22:in `run'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/rspec-core-2.11.1/lib/rspec/core/runner.rb:69:in `run'
from /Users/samanthacabral/.rvm/gems/ruby-1.9.3-p286#rails3tutorial/gems/rspec-core-2.11.1/lib/rspec/core/runner.rb:8:in `block in autorun'
I have also tried restarting spork and a few combinations suggested here for syntax with FactoryGirl.
HELP!!!!
You don't need to loop when create object in factory, and you can use sequence when define object same time, try this:
FactoryGirl.define do
factory :user do
sequence(:name) { |n| "User Name #{n}" }
sequence(:email) { |n| "person-#{n}#example.com" }
password "foobar"
password_confirmation "foobar"
end
factory :micropost do
content "Foo bar"
user
end
end
I think the problem is the way you’re declaring the factories by passing a block. Try declaring a micropost factory, for instance, this way:
factory :micropost do
content "Foo bar"
association :user
end

Rails Tutorial 3 Chapter 7: User Model Rspec Test Failing

I've been following the Rails Tutorial 3 successfully until I got to chapter 7 and implemented the user model, now my rspec keeps failing.
Here's my user.rb file output
class User < ActiveRecord::Base
attr_accessible :name, :email
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 => 6..40 }
before_save :encrypt_password
# Return tue if the user's password matches the submitted password.
def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return user if user.has_password?(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
Here's my users_spec.rb
require 'spec_helper'
describe User do
before(:each) do
#attr = {
:name => "Example User",
:email => "user#example.com",
:password => "foobar",
:password_confirmation => "foobar"
}
end
it "should create a new instance given a valid attribute" 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 address" 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 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 "passwords" do
before(:each) do
#user = User.create!(#attr)
end
it "should have a password attribute" do
#user.should respond_to(:password)
end
it "should have a password confirmation attribute" do
#user.should respond_to(:password_confirmation)
end
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
end
Finally here's the output of my rspec
Failures:
1) UsersController GET 'show' should be successfull
Failure/Error: #user = Factory(:user)
ArgumentError:
Factory not registered: user
# ./spec/controllers/users_controller_spec.rb:9:in `block (3 levels) in <top (required)>'
2) UsersController GET 'show' should find the right user
Failure/Error: #user = Factory(:user)
ArgumentError:
Factory not registered: user
# ./spec/controllers/users_controller_spec.rb:9:in `block (3 levels) in <top (required)>'
3) User should create a new instance given a valid attribute
Failure/Error: User.create!(#attr)
NoMethodError:
undefined method `password' for #<User:0x007f9d3684e0b0>
# ./spec/models/user_spec.rb:15:in `block (2 levels) in <top (required)>'
4) User should require a name
Failure/Error: no_name_user.should_not be_valid
NoMethodError:
undefined method `password' for #<User:0x007f9d36eacf38>
# ./spec/models/user_spec.rb:20:in `block (2 levels) in <top (required)>'
5) User should require an email address
Failure/Error: no_email_user.should_not be_valid
NoMethodError:
undefined method `password' for #<User:0x007f9d36e45978>
# ./spec/models/user_spec.rb:25:in `block (2 levels) in <top (required)>'
6) User should reject names that are too long
Failure/Error: long_name_user.should_not be_valid
NoMethodError:
undefined method `password' for #<User:0x007f9d36e0b2a0>
# ./spec/models/user_spec.rb:31:in `block (2 levels) in <top (required)>'
7) User should accept valid email addresses
Failure/Error: valid_email_user.should be_valid
NoMethodError:
undefined method `password' for #<User:0x007f9d36da4c80>
# ./spec/models/user_spec.rb:38:in `block (3 levels) in <top (required)>'
# ./spec/models/user_spec.rb:36:in `each'
# ./spec/models/user_spec.rb:36:in `block (2 levels) in <top (required)>'
8) User should reject invalid email addresses
Failure/Error: invalid_email_user.should_not be_valid
NoMethodError:
undefined method `password' for #<User:0x007f9d36d870b8>
# ./spec/models/user_spec.rb:46:in `block (3 levels) in <top (required)>'
# ./spec/models/user_spec.rb:44:in `each'
# ./spec/models/user_spec.rb:44:in `block (2 levels) in <top (required)>'
9) User should reject duplicate email addresses
Failure/Error: User.create!(#attr)
NoMethodError:
undefined method `password' for #<User:0x007f9d36c6c890>
# ./spec/models/user_spec.rb:51:in `block (2 levels) in <top (required)>'
10) User should reject email addresses identical up to case
Failure/Error: User.create!(#attr.merge(:email => upcased_email))
NoMethodError:
undefined method `password' for #<User:0x007f9d36c4d878>
# ./spec/models/user_spec.rb:58:in `block (2 levels) in <top (required)>'
11) User passwords should have a password attribute
Failure/Error: #user = User.create!(#attr)
NoMethodError:
undefined method `password' for #<User:0x007f9d36b3cda8>
# ./spec/models/user_spec.rb:66:in `block (3 levels) in <top (required)>'
12) User passwords should have a password confirmation attribute
Failure/Error: #user = User.create!(#attr)
NoMethodError:
undefined method `password' for #<User:0x007f9d369c27c0>
# ./spec/models/user_spec.rb:66:in `block (3 levels) in <top (required)>'
13) User password validations should require a password
Failure/Error: User.new(#attr.merge(:password => "", :password_confirmation => "")).
NoMethodError:
undefined method `password' for #<User:0x007f9d3699e5f0>
# ./spec/models/user_spec.rb:81:in `block (3 levels) in <top (required)>'
14) User password validations should require a matching password confirmation
Failure/Error: User.new(#attr.merge(:password_confirmation => "invalid")).
NoMethodError:
undefined method `password' for #<User:0x007f9d3698e600>
# ./spec/models/user_spec.rb:86:in `block (3 levels) in <top (required)>'
15) User password validations should reject short passwords
Failure/Error: User.new(hash).should_not be_valid
NoMethodError:
undefined method `password' for #<User:0x007f9d3697dda0>
# ./spec/models/user_spec.rb:93:in `block (3 levels) in <top (required)>'
16) User password validations should reject long passwords
Failure/Error: User.new(hash).should_not be_valid
NoMethodError:
undefined method `password' for #<User:0x007f9d3696c5a0>
# ./spec/models/user_spec.rb:99:in `block (3 levels) in <top (required)>'
Finished in 0.80301 seconds
35 examples, 16 failures, 2 pending
Failed examples:
rspec ./spec/controllers/users_controller_spec.rb:12 # UsersController GET 'show' should be successfull
rspec ./spec/controllers/users_controller_spec.rb:17 # UsersController GET 'show' should find the right user
rspec ./spec/models/user_spec.rb:14 # User should create a new instance given a valid attribute
rspec ./spec/models/user_spec.rb:18 # User should require a name
rspec ./spec/models/user_spec.rb:23 # User should require an email address
rspec ./spec/models/user_spec.rb:28 # User should reject names that are too long
rspec ./spec/models/user_spec.rb:34 # User should accept valid email addresses
rspec ./spec/models/user_spec.rb:42 # User should reject invalid email addresses
rspec ./spec/models/user_spec.rb:50 # User should reject duplicate email addresses
rspec ./spec/models/user_spec.rb:56 # User should reject email addresses identical up to case
rspec ./spec/models/user_spec.rb:69 # User passwords should have a password attribute
rspec ./spec/models/user_spec.rb:73 # User passwords should have a password confirmation attribute
rspec ./spec/models/user_spec.rb:80 # User password validations should require a password
rspec ./spec/models/user_spec.rb:85 # User password validations should require a matching password confirmation
rspec ./spec/models/user_spec.rb:90 # User password validations should reject short passwords
rspec ./spec/models/user_spec.rb:96 # User password validations should reject long passwords
Any ideas on what's going on? I've been stuck on this for about a week now
You don't have accessible password or password_confirmation properties on your model. Change:
attr_accessible :name, :email
to:
attr_accessible :name, :email, :password, :password_confirmation

Ruby On Rails 3 Tutorial Chap 8: Unit tests not passing

I'm working through Hartl's book and I'm up to chapter 8. I've written some tests that I believe should be passing. I've quadruple checked my code against what's in the book, and double checked it against what's in the book's github repo, but I'm stumped. I'm getting the following errors from RSpec:
Failures:
1) UsersController POST 'create' should redirect to the user "show" page
Failure/Error: response.should redirect_to(user_path(assigns(:user)))
ActionController::RoutingError:
No route matches {:action=>"show", :controller=>"users", :id=>#<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, encrypted_password: nil, salt: nil>}
# ./spec/controllers/users_controller_spec.rb:93:in `block (3 levels) in <top (required)>'
2) UsersController POST 'create' should have a welcome message
Failure/Error: flash[:success].should =~ /welcome to the sample app/i
expected: /welcome to the sample app/i
got: nil (using =~)
# ./spec/controllers/users_controller_spec.rb:98:in `block (3 levels) in <top (required)>'
Finished in 0.83875 seconds
46 examples, 2 failures
Like I said, I've checked the code again and again. Restarted spork, restarted rails server, ran without spork. I've checked it against the code in the book and in the github repo. I've even copy/pasted the spec and controller code in the github repo, but all to no avail.
I'm stumped. It's late and I need to crash. :)
Hopefully one of you guys can see something I'm not. Here's what I've got so far...
users_controller_spec.rb
require 'spec_helper'
describe UsersController do
render_views
# ...
describe "POST 'create'" do
# ...
describe 'success' do
before(:each) do
#attr = { :name => 'New User', :email => 'some-email#gmail.com', :password => 'foobar', :password_confirmation => 'foobar' }
end
it 'should create a new user' do
lambda do
post :create, :user => #attr
end.should change(User, :count).by(1)
end
end
it 'should redirect to the user "show" page' do
post :create, :user => #attr
response.should redirect_to(user_path(assigns(:user)))
end
it 'should have a welcome message' do
post :create, :user => #attr
flash[:success].should =~ /welcome to the sample app/i
end
end
end
users_controller.rb
class UsersController < ApplicationController
def new
#user = User.new
#title = 'Sign up'
end
def show
#user = User.find params[:id]
#title = #user.name
end
def create
#user = User.new(params[:user])
if #user.save
flash[:success] = 'Welcome to the Sample App!'
redirect_to #user
else
#title = 'Sign up'
render 'new'
end
end
end
user.rb
class User < ActiveRecord::Base
# Virtual properties (don't exist in db)
attr_accessor :password
# Accessible properties
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 }
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
before_save :encrypt_password
# Return true if the user's password matches the submitted password
def has_password?(submitted_password)
# Compare encrypted_password with the encrypted version of submitted_password
encrypted_password == encrypt(submitted_password)
end
# Static/Class methods
def self.authenticate(email, submitted_password)
user = find_by_email email
return nil if user.nil?
return user if user.has_password? submitted_password
end
# Private functionality.
# Anything after the 'private' pragma will be inaccessable from outside the class
private
def encrypt_password
self.salt = make_salt if new_record? # Using ActiveRecord goodness to make sure this only gets created once.
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
routes.rb
SampleApp::Application.routes.draw do
#get '/users/new'
resources :users
match '/signup' => 'users#new'
match '/about' => 'pages#about'
match '/contact' => 'pages#contact'
match '/help' => 'pages#help'
root :to => 'pages#home'
end
Thanks in advance. If you guys really want to dig through or if I've missed something in my post, here's my code.
I'm very new to rails, and absolutely love it so far. Any help will be greatly appreciated.
Look closely at your users_controller_spec "success" spec: when will it create #attr? Before each test, or just before the "should create a new user" test? You use it in all the "POST 'create'" tests...
Once you make that non-spec-specific your tests will pass.
(By the way, having the code up in git is handy, but only if the code you're posting is actually checked in, otherwise... not as much ;)
your
it "should redirect to the user show page"
and
it "should have a welcome message"
is outside of the
describe "success" do
loop

DRY Problem with Rspec how can i fix it

i am new in Ruby and Rspec. I am writing my first RSpec test and i think that my code is not very well. But i don't know how i can make it better.
In this file i will check my Address class. The first_name and last_name are the same but i have two big blocks for it. How can i refactor my code? And what is a good way to check RegExp.
Thank you.
specify { Factory.build(:address).should be_valid }
### first_name ###
it "should be invalid without an first_name" do
Factory.build(:address, :first_name => nil).should_not be_valid
end
context "first_name" do
it "should be invalid with more than 20 chars" do
Factory.build(:address, :first_name => "#{'b'*21}").should_not be_valid
end
it "should be invalid with less than 3 chars" do
Factory.build(:address, :first_name => "ll").should_not be_valid
end
it "should be valid with an valid first_name" do
valid_names.each do |name|
Factory.build(:address, :first_name => name).should be_valid
end
end
it "should be invalid with an invalid first_name" do
invalid_names.each do |name|
Factory.build(:address, :first_name => name).should_not be_valid
end
end
end
### last_name ###
it "should be invalid without an last_name" do
Factory.build(:address, :last_name => nil).should_not be_valid
end
context "last_name" do
it "should be invalid with more than 20 chars" do
Factory.build(:address, :last_name => "#{'b'*21}").should_not be_valid
end
it "should be invalid with less than 3 chars" do
Factory.build(:address, :last_name => "ll").should_not be_valid
end
it "should be valid with an valid last_name" do
valid_names.each do |name|
Factory.build(:address, :last_name => name).should be_valid
end
end
it "should be invalid with an invalid last_name" do
invalid_names.each do |name|
Factory.build(:address, :last_name => name).should_not be_valid
end
end
end
def valid_names
["Kai","Ülück's","Schmeißtzs","Rald","Dr. Franzen","rolfes","Lars Michael","Öcück","Mark-Anthony"]
end
def invalid_names
["-#+*32"," ","a& &lkdf","_-_.l##df"," aaadsa","M€lzer"]
end
so here's the way I sometimes do this kind of thing:
describe Address do
describe "validations" do
before do
#address = Factory(:address)
end
describe "#first_name" do
#prove that your factory is correct
it "should be valid" do
#address.should be_valid
end
it "should be less than 20 chars" do
#address.name = "0" * 20
#address.should_not be_valid
end
it "should be more than 3 chars" do
#address.name = "000"
#address.should_not be_valid
end
end
end
end
Remember that your tests don't need to be really DRY. Don't sacrifice readability for it.
Think of your specs as examples: which examples should be valid and which shouldn't? That's also the clue to testing regexes: provide some examples that pass and some that don't.
For validations, I made some custom matchers, which can be found here. Example:
describe Address do
it { should deny(:last_name).to_be(nil, "", "1", "br", "a& &lkdf","_-_.l##df", "lzer") }
it { should allow(:last_name).to_be("Kai","Ülück's","Schmeißtzs","Rald","Dr. Franzen","rolfes","Lars Michael","Öcück","Mark-Anthony") }
end

Resources