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
Related
Earlier I was having single factory for user and it worked fine.
But now, I want two sets of factories for user's data , one with encrypted details and other one with plain text user details.
This is the code I am using:
FactoryBot.define do
factory :user do
trait :encryption do
email AESCrypt.encrypt(Faker::Internet.email, ENV["AES_KEY"])
password AESCrypt.encrypt("password", ENV["AES_KEY"])
password_confirmation AESCrypt.encrypt("password",ENV["AES_KEY"])
username Faker::Name.name
end
trait :unencrypted_user_details do
email Faker::Internet.email
password "password"
password_confirmation "password"
username Faker::Name.name
end
end
end
And using the same as in spec file:
user = FactoryBot.create(:user,:unencrypted_user_details)
But I am getting the following error while running the spec:
NoMethodError:
undefined method `name=' for #<User:0x00000006d512f8>
The User model does not have a field "name" instead "username" is there.
Error Stacktrace:
F
Failures:
1) Api::V2::UserApp::UsersController Generate Pin API generates a new pin for the user
Failure/Error: user = FactoryBot.create(:unencrypted_user_details)
NoMethodError:
undefined method `name=' for #<User:0x0000000664cbb0>
Did you mean? name
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/activemodel-4.2.7.1/lib/active_model/attribute_methods.rb:433:in `method_missing'
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/factory_bot-4.8.2/lib/factory_bot/attribute_assigner.rb:16:in `public_send'
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/factory_bot-4.8.2/lib/factory_bot/attribute_assigner.rb:16:in `block (2 levels) in object'
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/factory_bot-4.8.2/lib/factory_bot/attribute_assigner.rb:15:in `each'
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/factory_bot-4.8.2/lib/factory_bot/attribute_assigner.rb:15:in `block in object'
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/factory_bot-4.8.2/lib/factory_bot/attribute_assigner.rb:14:in `tap'
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/factory_bot-4.8.2/lib/factory_bot/attribute_assigner.rb:14:in `object'
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/factory_bot-4.8.2/lib/factory_bot/evaluation.rb:13:in `object'
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/factory_bot-4.8.2/lib/factory_bot/strategy/create.rb:9:in `result'
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/factory_bot-4.8.2/lib/factory_bot/factory.rb:43:in `run'
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/factory_bot-4.8.2/lib/factory_bot/factory_runner.rb:29:in `block in run'
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/activesupport-4.2.7.1/lib/active_support/notifications.rb:166:in `instrument'
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/factory_bot-4.8.2/lib/factory_bot/factory_runner.rb:28:in `run'
# /home/xxxxxxxxx/.rvm/gems/ruby-2.3.3/gems/factory_bot-4.8.2/lib/factory_bot/strategy_syntax_method_registrar.rb:20:in `block in define_singular_strategy_method'
# ./spec/controllers/user_app/users_controller.rb:43:in `block (3 levels) in <top (required)>'
Finished in 0.37745 seconds (files took 4.26 seconds to load)
3 examples, 1 failure
user_spec.rb
describe "Generate Pin API" do
it "generates a new pin for the user" do
user = FactoryBot.create(:unencrypted_user_details) #line 43
client = user.client
request.env["HTTP_AUTHORIZATION"] = user.auth_token
get :generate_pin
response_json = JSON.parse(response.body)
expect(response_json["response_code"]).to eq(200)
end
end
Controller Code
def generate_pin
phone = ValidatePhone.find_by(phone_no: #client.phone_no)
phone.present? ? phone.update_attributes(is_verified: true) : ValidatePhone.create(phone_no: #client.phone_no)
sms_text = "Hello"
send_sms(#client.phone_no,sms_text)
render :json => {
:response_code => 200,
:response_message => "Welcome Onboard."
}
end
Is this the correct way to create multiple factories and why am I getting this error undefined method name?
This is not the way to create variable factories. You must use brackets for fields on which value is the result fo a call:
FactoryBot.define do
factory :user do
trait :encryption do
email { AESCrypt.encrypt(Faker::Internet.email, ENV["AES_KEY"]) }
password { AESCrypt.encrypt("password", ENV["AES_KEY"]) }
password_confirmation { AESCrypt.encrypt("password",ENV["AES_KEY"]) }
username { Faker::Name.name }
end
trait :unencrypted_user_details do
email { Faker::Internet.email }
password "password"
password_confirmation "password"
username { Faker::Name.name }
end
end
end
Take a look at the guides:
https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#traits
I'm using rails 3.2 with devise and rspec with factory girl. I'm trying to log a user in but it seems there is a problem creating the user in the first place.
user factory:
factory :user do
first_name "Test"
last_name "User"
sequence(:email) { |n| "foo#{n}#test.com" }
password "secretpassword"
confirmed_at Time.now
end
my spec
feature "BackOffice" do
subject { page }
context "as user" do
let(:user) { create(:user) }
describe "should not have access to backoffice" do
before do
visit "http://domain_name/fr/users/sign_in"
within ".login-wrapper" do
fill_in "user_email", with: user.email
fill_in "user_password", with: user.password
click_button "S'identifier"
end
end
it { should have_content "Bienvenue"}
end
end
Error
Failure/Error: let(:user) { create(:user) }
ActionView::Template::Error:
No route matches {:action=>"edit", :controller=>"users/registrations"}
# ./app/views/user_mailer/welcome.html.erb:3:in `_app_views_user_mailer_welcome_html_erb__212088972377821759_70301344598820'
# ./app/mailers/user_mailer.rb:31:in `welcome'
# ./app/models/user.rb:125:in `send_welcome_email'
# ./spec/requests/backoffice_spec.rb:15:in `block (3 levels) in <top (required)>'
# ./spec/requests/backoffice_spec.rb:20:in `block (5 levels) in <top (required)>'
# ./spec/requests/backoffice_spec.rb:19:in `block (4 levels) in <top (required)>'
# ./spec/support/database_cleaner.rb:17:in `block (2 levels) in <top (required)>'
why would it be trying to go to the edit action when it should be creating the resource?
There was a problem with a link in a welcome email I added the following to fix it:
config.action_mailer.default_url_options = { protocol: "http", host: "localhost", port: 3000, locale: I18n.locale }
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!
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
I've added a :username_or_email property to my User model as such:
class User < ActiveRecord::Base
#authlogic
acts_as_authentic do |c|
c.login_field = :username_or_email
end
#virtual field for allowing a user to login with their username or email
attr_accessor :username_or_email
attr_accessible :username, :email, :password, :password_confirmation, :username_or_email
validates :username, :presence => true,
:length => { :within => 3..20 },
:uniqueness => true,
:format => { :with => /\A[a-z0-9][a-z0-9\-]+[a-z0-9]\z/ }
validates :email, :presence => true,
:format => { :with => /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i },
:uniqueness => { :case_sensative => false }
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
def self.find_by_username_or_email(username_or_email)
User.find_by_username(username_or_email) || User.find_by_email(username_or_email)
end
end
The purpose of this is to create a virtual field which allows the user to log in with either their username or email using Authlogic. This works perfectly when I run the server, doing exactly what I want it to. However, it causes all of the following specs to fail:
require 'spec_helper'
describe User do
before(:each) do
#attr = {
:username => "example",
:email => "user#example.com",
:password => "password",
:password_confirmation => "password"
}
end
describe "username validations" do
it "should allow usernames with numbers" do
User.create!(#attr.merge(:username => 'example123'))
end
it "should allow hyphens" do
User.create!(#attr.merge(:username => 'example-two'))
end
it "should require a username" do
no_username_user = User.new (#attr.merge(:username => ""))
no_username_user.should_not be_valid
end
it "should reject usernames that are too long" do
user = User.new(#attr.merge(:username => ("a" * 21)))
user.should_not be_valid
end
it "should reject username that are too short" do
user = User.new(#attr.merge(:username => ("a" * 2)))
user.should_not be_valid
end
it "should reject username with uppercase letters" do
user = User.new(#attr.merge(:username => "Example"))
user.should_not be_valid
end
it "should reject duplicate usernames" do
User.create!(#attr)
user = User.new(#attr.merge(:email => "user2#example.com"))
user.should_not be_valid
end
it "should reject usernames with whitespace characters" do
u1 = User.new(#attr.merge(:username => "exa mple"))
u2 = User.new(#attr.merge(:username => " example"))
u3 = User.new(#attr.merge(:username => "example "))
u4 = User.new(#attr.merge(:username => "exa\tmple"))
u5 = User.new(#attr.merge(:username => "exa\nmple"))
u1.should_not be_valid
u2.should_not be_valid
u3.should_not be_valid
u4.should_not be_valid
u5.should_not be_valid
end
it "should reject usernames with special characters" do
u1 = User.new(#attr.merge(:username => 'ex&mple'))
u2 = User.new(#attr.merge(:username => 'ex*mple'))
u3 = User.new(#attr.merge(:username => 'ex"mple'))
u4 = User.new(#attr.merge(:username => 'ex^mple'))
u5 = User.new(#attr.merge(:username => 'ex;mple'))
u1.should_not be_valid
u2.should_not be_valid
u3.should_not be_valid
u4.should_not be_valid
u5.should_not be_valid
end
it "should reject usernames that begin with a hypen" do
user = User.new(#attr.merge(:username => '-example'))
user.should_not be_valid
end
it "should reject usernames that end with a hypen" do
user = User.new(#attr.merge(:username => 'example-'))
user.should_not be_valid
end
end
describe "email validations" do
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 duplicate emails" do
User.create!(#attr)
user2 = User.new(#attr.merge(:username => "example2"))
user2.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 email address idential up to case" do
User.create!(#attr)
user = User.new(#attr.merge(:email => #attr[:email].capitalize))
user.should_not be_valid
end
end
describe "password validations" do
it "should require a password or a password confirmation" do
user = User.new(#attr.merge(:password => "", :password_confirmation => ""))
user.should_not be_valid
end
it "should require a password" do
user = User.new(#attr.merge(:password => ""))
user.should_not be_valid
end
it "should require a password confirmation" do
user = User.new(#attr.merge(:password_confirmation => ""))
user.should_not be_valid
end
it "should require a matching password confirmation" do
user = User.new(#attr.merge(:password_confirmation => "invalid"))
user.should_not be_valid
end
it "should reject passwords that are too short" do
password = "a" * 5
user = User.new(#attr.merge(:password => password, :password_confirmation => password))
user.should_not be_valid
end
it "should reject passwords that are too long" do
password = "a" * 41
user = User.new(#attr.merge(:password => password, :password_confirmation => password))
user.should_not be_valid
end
it "should require case sensative password confirmations" do
password = "password"
user = User.new(#attr.merge(:password => password,
:password_confirmation => password.capitalize))
user.should_not be_valid
end
end
end
They fails with the errors:
Running: spec/models/user_spec.rb
FFFFFFFFFFFFFFFFFFFFFFF
Failures:
1) User username validations should allow usernames with numbers
Failure/Error: User.create!(#attr.merge(:username => 'example123'))
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x000001017c1850>
# ./spec/models/user_spec.rb:17:in `block (3 levels) in <top (required)>'
2) User username validations should allow hyphens
Failure/Error: User.create!(#attr.merge(:username => 'example-two'))
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x00000100d50f10>
# ./spec/models/user_spec.rb:21:in `block (3 levels) in <top (required)>'
3) User username validations should require a username
Failure/Error: no_username_user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x00000100cc9da8>
# ./spec/models/user_spec.rb:26:in `block (3 levels) in <top (required)>'
4) User username validations should reject usernames that are too long
Failure/Error: user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x00000100c333f8>
# ./spec/models/user_spec.rb:31:in `block (3 levels) in <top (required)>'
5) User username validations should reject username that are too short
Failure/Error: user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x00000100aafbd0>
# ./spec/models/user_spec.rb:36:in `block (3 levels) in <top (required)>'
6) User username validations should reject username with uppercase letters
Failure/Error: user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x000001032e2f58>
# ./spec/models/user_spec.rb:41:in `block (3 levels) in <top (required)>'
7) User username validations should reject duplicate usernames
Failure/Error: User.create!(#attr)
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x00000103167f70>
# ./spec/models/user_spec.rb:45:in `block (3 levels) in <top (required)>'
8) User username validations should reject usernames with whitespace characters
Failure/Error: u1.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x000001032dbb40>
# ./spec/models/user_spec.rb:57:in `block (3 levels) in <top (required)>'
9) User username validations should reject usernames with special characters
Failure/Error: u1.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x0000010328d0d0>
# ./spec/models/user_spec.rb:71:in `block (3 levels) in <top (required)>'
10) User username validations should reject usernames that begin with a hypen
Failure/Error: user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x0000010323f3d0>
# ./spec/models/user_spec.rb:80:in `block (3 levels) in <top (required)>'
11) User username validations should reject usernames that end with a hypen
Failure/Error: user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x00000103212a10>
# ./spec/models/user_spec.rb:85:in `block (3 levels) in <top (required)>'
12) User email validations should require an email
Failure/Error: no_email_user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x000001031ed4e0>
# ./spec/models/user_spec.rb:96:in `block (3 levels) in <top (required)>'
13) User email validations should reject duplicate emails
Failure/Error: User.create!(#attr)
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x000001031bf630>
# ./spec/models/user_spec.rb:100:in `block (3 levels) in <top (required)>'
14) User email validations should accept valid email addresses
Failure/Error: valid_email_user.should be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x000001031991b0>
# ./spec/models/user_spec.rb:109:in `block (4 levels) in <top (required)>'
# ./spec/models/user_spec.rb:107:in `each'
# ./spec/models/user_spec.rb:107:in `block (3 levels) in <top (required)>'
15) User email validations should reject invalid email addresses
Failure/Error: invalid_email_user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x0000010315d1b0>
# ./spec/models/user_spec.rb:117:in `block (4 levels) in <top (required)>'
# ./spec/models/user_spec.rb:115:in `each'
# ./spec/models/user_spec.rb:115:in `block (3 levels) in <top (required)>'
16) User email validations should reject email address idential up to case
Failure/Error: User.create!(#attr)
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x0000010310a898>
# ./spec/models/user_spec.rb:122:in `block (3 levels) in <top (required)>'
17) User password validations should require a password or a password confirmation
Failure/Error: user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x0000010172f2c0>
# ./spec/models/user_spec.rb:135:in `block (3 levels) in <top (required)>'
18) User password validations should require a password
Failure/Error: user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x000001015f5b98>
# ./spec/models/user_spec.rb:140:in `block (3 levels) in <top (required)>'
19) User password validations should require a password confirmation
Failure/Error: user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x0000010155f120>
# ./spec/models/user_spec.rb:145:in `block (3 levels) in <top (required)>'
20) User password validations should require a matching password confirmation
Failure/Error: user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x00000101310298>
# ./spec/models/user_spec.rb:150:in `block (3 levels) in <top (required)>'
21) User password validations should reject passwords that are too short
Failure/Error: user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x00000100eecbf8>
# ./spec/models/user_spec.rb:156:in `block (3 levels) in <top (required)>'
22) User password validations should reject passwords that are too long
Failure/Error: user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x00000100d7f400>
# ./spec/models/user_spec.rb:162:in `block (3 levels) in <top (required)>'
23) User password validations should require case sensative password confirmations
Failure/Error: user.should_not be_valid
NoMethodError:
undefined method `username_or_email_changed?' for #<User:0x00000100cf0b38>
# ./spec/models/user_spec.rb:169:in `block (3 levels) in <top (required)>'
Finished in 0.19613 seconds
23 examples, 23 failures
It seems like the problem is occurring with the valid? method, but I don't understand why considering :username_or_email doesn't have any validations in place. Why are these errors occurring and how can I fix them?
Thanks.
I would guess that because username_or_email is not an attribute in the ActiveRecord sense, it should not be mentioned with attr_accessible.
The solution was actually pretty simple. In user.rb:
class User < ActiveRecord::Base
#authlogic
acts_as_authentic do |c|
c.login_field = :username_or_email
c.validates_login_field = false
end
...
end
The documentation for this method can be found here.