how to get methods via has_one and belongs_to assocation? - ruby-on-rails

I have few weeks experience or close to a month learning on Ruby on Rails. I hope to understand why I can't get methods via associated objects.
I am attempting to get associated objects attached to user instead of stane alone Profile.new e.g. profile with its methods as seen just below.
user.profile.create
user.profile.create!
user.profile.build
instead i get RSpec error messages. NoMethodError:undefined method `build' for nil:NilClass
Thanks kindly in advance
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class User < ActiveRecord::Base
attr_accessible :email
has_one :profile
before_save { |user| user.email = email.downcase }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
end
.
# == Schema Information
#
# Table name: profiles
#
# id :integer not null, primary key
# given_name :string(255)
# surname :string(255)
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Profile < ActiveRecord::Base
attr_accessible :given_name, :surname #, :user_id
belongs_to :user
validates :user_id, presence: true
end
.
smileymike#ubuntu:~/rails_projects/bffmApp$ bundle exec guard
Guard uses Libnotify to send notifications.
Guard is now watching at '/home/smileymike/rails_projects/bffmApp'
Starting Spork for RSpec
Using RSpec
Preloading Rails environment
Loading Spork.prefork block...
Spork is ready and listening on 8989!
Spork server for RSpec successfully started
Guard::RSpec is running, with RSpec 2!
Running all specs
Running tests with args ["--drb", "-f", "progress", "-r", "/home/smileymike/.rvm/gems/ruby-1.9.3-p194/gems/guard-rspec-0.7.2/lib/guard/rspec/formatters/notification_rspec.rb", "-f", "Guard::RSpec::Formatter::NotificationRSpec", "--out", "/dev/null", "--failure-exit-code", "2", "spec"]...
......FFFFFFFF...............
Failures:
1) Profile
Failure/Error: before { #profile = user.profile.build(given_name: "Michael", surname: "Colin") }
NoMethodError:
undefined method `build' for nil:NilClass
# ./spec/models/profile_spec.rb:23:in `block (2 levels) in <top (required)>'
2) Profile
Failure/Error: before { #profile = user.profile.build(given_name: "Michael", surname: "Colin") }
NoMethodError:
undefined method `build' for nil:NilClass
# ./spec/models/profile_spec.rb:23:in `block (2 levels) in <top (required)>'
3) Profile
Failure/Error: before { #profile = user.profile.build(given_name: "Michael", surname: "Colin") }
NoMethodError:
undefined method `build' for nil:NilClass
# ./spec/models/profile_spec.rb:23:in `block (2 levels) in <top (required)>'
4) Profile
Failure/Error: before { #profile = user.profile.build(given_name: "Michael", surname: "Colin") }
NoMethodError:
undefined method `build' for nil:NilClass
# ./spec/models/profile_spec.rb:23:in `block (2 levels) in <top (required)>'
5) Profile
Failure/Error: before { #profile = user.profile.build(given_name: "Michael", surname: "Colin") }
NoMethodError:
undefined method `build' for nil:NilClass
# ./spec/models/profile_spec.rb:23:in `block (2 levels) in <top (required)>'
6) Profile user
Failure/Error: before { #profile = user.profile.build(given_name: "Michael", surname: "Colin") }
NoMethodError:
undefined method `build' for nil:NilClass
# ./spec/models/profile_spec.rb:23:in `block (2 levels) in <top (required)>'
7) Profile when user_id is not present
Failure/Error: before { #profile = user.profile.build(given_name: "Michael", surname: "Colin") }
NoMethodError:
undefined method `build' for nil:NilClass
# ./spec/models/profile_spec.rb:23:in `block (2 levels) in <top (required)>'
8) Profile accessible attributes should not allow access to user_id
Failure/Error: before { #profile = user.profile.build(given_name: "Michael", surname: "Colin") }
NoMethodError:
undefined method `build' for nil:NilClass
# ./spec/models/profile_spec.rb:23:in `block (2 levels) in <top (required)>'
Finished in 1.56 seconds
29 examples, 8 failures
Failed examples:
rspec ./spec/models/profile_spec.rb:27 # Profile
rspec ./spec/models/profile_spec.rb:28 # Profile
rspec ./spec/models/profile_spec.rb:29 # Profile
rspec ./spec/models/profile_spec.rb:30 # Profile
rspec ./spec/models/profile_spec.rb:33 # Profile
rspec ./spec/models/profile_spec.rb:31 # Profile user
rspec ./spec/models/profile_spec.rb:37 # Profile when user_id is not present
rspec ./spec/models/profile_spec.rb:41 # Profile accessible attributes should not allow access to user_id
Done.
>
.
require 'spec_helper'
describe Profile do
# before do
# This code is wrong but it works
# #profile = Profile.new(given_name: "Michael", surname: "Colin", user_id: user.id)
# end
# but I am attempting to create a profile via User/Profile assoications
let(:user) { FactoryGirl.create(:user) }
before { #profile = user.profile.build(given_name: "Michael", surname: "Colin") }
subject { #profile }
it { should respond_to(:given_name) }
it { should respond_to(:surname) }
it { should respond_to(:user_id) }
it { should respond_to(:user) }
its(:user) { should == user }
it { should be_valid }
describe "when user_id is not present" do
before { #profile.user_id = nil }
it { should_not be_valid }
end
describe "accessible attributes" do
it "should not allow access to user_id" do
expect do
Profile.new(user_id: user_id)
end.should raise_error(ActiveModel::MassAssignmentSecurity::Error)
end
end
end

has_one will give you a build_profile method on user. See http://guides.rubyonrails.org/association_basics.html#has_one-association-reference for more details.
The reason you can't do user.profile.build is that there is no profile, so user.build returns nil and it doesn't make sense to ask nil to build a profile. This is different to the has_many case, where out always returns a collection of things - even when the collection is empty - and you can ask the collection to make another member. It's easy to imagine the has_one accessor returning a non-nil "I'm not here" value, which would enable your scenario, but would have other issues (mainly that such a value would not be falsey, leading to arguably less rubyesque code)

Related

Create Multiple Factories for User

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

Solidus: Code that is executed in after_save callback returns error in rspec

I'm using latest version of Solidus e-commerce (fork of Spree) and I'm having this issue. To describe it quickly:
In Admin I create Spree::Membership record
after_save callback in Spree::Membership creates Product and 2 variants
This code works when I run the server, but when I'm trying to use Rspec it gives me this error:
Failure/Error: reload.product.setup_membership_variants
NoMethodError:
undefined method `setup_membership_variants' for nil:NilClass
# ./app/models/spree/membership.rb:26:in `block in setup_product'
# ./app/models/spree/membership.rb:18:in `setup_product'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/configuration.rb:18:in `block in initialize'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/evaluation.rb:15:in `create'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/strategy/create.rb:12:in `block in result'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/strategy/create.rb:9:in `tap'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/strategy/create.rb:9:in `result'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/factory.rb:42:in `run'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/factory_runner.rb:29:in `block in run'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/factory_runner.rb:28:in `run'
# /box/gems/factory_girl-4.8.0/lib/factory_girl/strategy_syntax_method_registrar.rb:20:in `block in define_singular_strategy_method'
# ./spec/controllers/spree/premium_controller_spec.rb:4:in `block (2 levels) in <top (required)>'
# ./spec/controllers/spree/premium_controller_spec.rb:33:in `block (6 levels) in <top (required)>'
# ./spec/controllers/spree/premium_controller_spec.rb:53:in `block (8 levels) in <top (required)>'
# ./spec/controllers/spree/premium_controller_spec.rb:53:in `block (7 levels) in <top (required)>'
Here is code I'm using:
membership.rb
class Spree::Membership < Spree::Base
has_many :active_memberships, class_name: 'Spree::ActiveMembership', dependent: :destroy
has_one :membership_product, class_name: "Spree::MembershipProduct", dependent: :destroy
has_one :product, through: :membership_product, source: :product
validates :name, presence: true
validates :monthly_quota, presence: true
validates :price, presence: true
after_save :setup_product
private
def setup_product
if product.nil?
ActiveRecord::Base.transaction do
create_membership_product(
product: Spree::Product.create(
name: name,
price: price,
shipping_category: Spree::ShippingCategory.find_by(name: "Default")
)
)
reload.product.setup_membership_variants
end
else
product.update(name: name, price: price)
end
end
end
product_decorator.rb
Spree::Product.class_eval do
def setup_membership_variants
ot = Spree::OptionType.find_or_create_by(name: "Membership")
option_types << ot
if ot.option_values.empty?
["Monthly", "Yearly"].each do |freq|
ot.option_values.create(name: freq, presentation: freq)
end
end
month = variants.create(is_master: false, price: price, track_inventory: false)
month.option_values << Spree::OptionValue.find_by(name: "Monthly")
year = variants.create(is_master: false, price: price * 12, track_inventory: false)
year.option_values << Spree::OptionValue.find_by(name: "Yearly")
end
end
membership.rb factory
FactoryGirl.define do
factory :membership, class: Spree::Membership do
name {FFaker::Lorem.word}
monthly_quota { rand(10..200) }
price { rand(10..200) }
trait :unnamed do
name nil
end
trait :without_quota do
monthly_quota nil
end
trait :priceless do
price nil
end
end
end
example of controller test
require 'rails_helper'
RSpec.describe Spree::PremiumController, type: :controller do
let(:valid_membership) { create(:membership) }
let(:variant) { create(:master_variant) }
context "#show" do
it "returns http success" do
get :show
expect(response).to have_http_status(:success)
end
it "returns all memberships" do
get :show
expect(assigns[:memberships]).to include(valid_membership)
end
end
context "#create" do
let!(:store) { create(:store) }
context "user not logged" do
context "valid attributes" do
context "user doesn't exist in database" do
subject do
post(:create, params: {
premium: {
first_name: "Ondrej",
last_name: "Kubala",
email: "ondrej#bala.com",
password: "test123",
password_confirmation: "test123",
membership_id: valid_membership.id,
payment_frequency: "1", #monthly yearly is 2
cc_number: "4111111111111111",
cc_exp_date: "10/22",
cvv: "123"
}
})
end
it "creates user with valid attributes" do
expect { subject }.to change { Spree::User.count }.from(0).to(1)
end
it "logs in user" do
expect(controller.warden).to receive(:set_user)
subject
end
context "create order with variant" do
it "should handle population" do
expect { subject }.to change { Spree::Order.count }.by(1)
user = Spree::User.find_by email: "ondrej#bala.com"
order = user.orders.last
expect(response).to redirect_to go_premium_path
expect(order.line_items.size).to eq(1)
# line_item = order.line_items.first
# expect(line_item.variant_id).to eq(valid_membership.reload.product.variants.)
end
it "charges credit card"
it "should redirect to account page"
end
end
context "user already exists"
end
context "wrong user attributes" do
end
context "wrong payment attributes" do
end
end
context "user is logged in" do
let(:user) { create(:user) }
before do
allow(controller).to receive_messages try_spree_current_user: user
allow(controller).to receive_messages spree_current_user: user
end
it "doesn't create user"
end
end
end
I don't have too much experience in Rspec, but it's weird that it works when server is running in development but in test it gives me that error.
Any idea what is wrong?
My guess would be that product creation call fails for some reason.
Try bang version(product: Spree::Product.create!) to have the error thrown when it occurs.
If product indeed gets created, use pry or byebug to figure out why after reload membership, product is not associated with membership.

Rspec and current user id saved in different model from devise

I'm using Devise to manage users and my goal get the current user to be saved with the created record.
The current user is saved in the controller but my Rspec is wrong!
Thank you all for your help.
My record Model
class Record < ActiveRecord::Base
#Associations
belongs_to :user
# Validations
validates :title, :user, presence: true
end
My record Controller
class RecordsController < ApplicationController
before_action :find_record, only: [:show, :edit, :update, :destroy]
def create
#record = Record.new(record_params)
if #record.save
redirect_to #record
else
#records = Record.all
render 'index'
end
end
def update
if #record.update(record_params)
flash[:notice] = "The record was updated successfully"
redirect_to #record
else
render 'edit'
end
end
private
def find_record
#record = Record.find(params[:id])
end
def record_params
params.require(:record).permit(:title, :description, :user_id).merge(user: current_user) # as suggested
end
end
My Rspec
require 'rails_helper'
describe RecordsController do
let(:record) { create(:record) }
let(:user) { create(:user) }
let(:title) { "Some title I would like to put in my record" }
let(:description) { "description I would like to put in my record" }
describe "#create" do
it "creates a new record with the given title and description" do
expect do
post :create, record: { title: title, description: description, user_id: user }
end.to change { Record.count }.by(1)
expect(response).to redirect_to(assigns[:record])
expect(assigns[:record].title).to eq(title)
expect(assigns[:record].description).to eq(description)
end
it "fails to create a record and returns to the index page" do
expect(post :create, record: { description: description }).to render_template(:index)
expect(assigns[:records]).to eq(Record.all)
end
end
describe "#update" do
it "find the records and sets the new given values" do
put :update, { id: record.id, record: { title: title, description: description } }
record.reload
expect(record.title).to eq(title)
expect(record.description).to eq(description)
expect(flash[:notice]).to eq("The record was updated successfully")
end
it "fails to create a record and returns to the edit page" do
expect(put :update, { id: record.id, record: { title: "" } }).to render_template(:edit)
end
end
end
Now with the current user being saved Rspec throws me errors in create and update:
1) RecordsController#create creates a new record with the given title and description
Failure/Error: post :create, record: { title: title, description: description, user_id: user }
NoMethodError:
undefined method `authenticate' for nil:NilClass
# ./app/controllers/records_controller.rb:42:in `record_params'
# ./app/controllers/records_controller.rb:9:in `create'
# ./spec/controllers/records_controller_spec.rb:36:in `block (4 levels) in <top (required)>'
# ./spec/controllers/records_controller_spec.rb:35:in `block (3 levels) in <top (required)>'
# -e:1:in `<main>'
2) RecordsController#create fails to create a record and returns to the index page
Failure/Error: expect(post :create, record: { description: description }).to render_template(:index)
NoMethodError:
undefined method `authenticate' for nil:NilClass
# ./app/controllers/records_controller.rb:42:in `record_params'
# ./app/controllers/records_controller.rb:9:in `create'
# ./spec/controllers/records_controller_spec.rb:46:in `block (3 levels) in <top (required)>'
# -e:1:in `<main>'
3) RecordsController#update find the records and sets the new given values
Failure/Error: put :update, { id: record.id, record: { title: title, description: description } }
NoMethodError:
undefined method `authenticate' for nil:NilClass
# ./app/controllers/records_controller.rb:42:in `record_params'
# ./app/controllers/records_controller.rb:20:in `update'
# ./spec/controllers/records_controller_spec.rb:62:in `block (3 levels) in <top (required)>'
# -e:1:in `<main>'
4) RecordsController#update fails to create a record and returns to the edit page
Failure/Error: expect(put :update, { id: record.id, record: { title: "" } }).to render_template(:edit)
NoMethodError:
undefined method `authenticate' for nil:NilClass
# ./app/controllers/records_controller.rb:42:in `record_params'
# ./app/controllers/records_controller.rb:20:in `update'
# ./spec/controllers/records_controller_spec.rb:72:in `block (3 levels) in <top (required)>'
You need to login the user first before you can use the current_user.
Something like:
before do
sign_in :user, create(:user)
end
Also checkout How To: Test controllers with Rails 3 and 4 (and RSpec)

Rake db:seed NoMethodError: undefined method `sample'

I am trying to seed my database, but I am running into this error, and as a beginner do not know how to fix it. I'm trying to take a sample of bookmarks and assign them to some of my users. Any ideas why this is throwing an error? Here is the error:
vagrant#rails-dev-box:~/code/bookmarks$ rake db:seed
rake aborted!
NoMethodError: undefined method `sample' for #<Class:0xaa90cf4>
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activerecord-4.0.5/lib/active_record/dynamic_matchers.rb:22:in `method_missing'
/home/vagrant/code/bookmarks/db/seeds.rb:47:in `block (2 levels) in <top (required)>'
/home/vagrant/code/bookmarks/db/seeds.rb:46:in `times'
/home/vagrant/code/bookmarks/db/seeds.rb:46:in `block in <top (required)>'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activerecord-4.0.5/lib/active_record/relation/delegation.rb:13:in `each'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activerecord-4.0.5/lib/active_record/relation/delegation.rb:13:in `each'
/home/vagrant/code/bookmarks/db/seeds.rb:45:in `<top (required)>'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.5/lib/active_support/dependencies.rb:223:in `load'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.5/lib/active_support/dependencies.rb:223:in `block in load'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.5/lib/active_support/dependencies.rb:214:in `load_dependency'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.5/lib/active_support/dependencies.rb:223:in `load'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.5/lib/rails/engine.rb:540:in `load_seed'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activerecord-4.0.5/lib/active_record/tasks/database_tasks.rb:154:in `load_seed'
/home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activerecord-4.0.5/lib/active_record/railties/databases.rake:181:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:seed
Edit: Here is my seeds.rb file:
require 'faker'
# Create a User
# user = User.new(
# name: 'First Last',
# email: 'firstlast#gmail.com',
# password: 'password',
# )
# user.skip_confirmation!
# user.save
#Create Users
5.times do
user = User.new(
name: Faker::Name.name,
email: Faker::Internet.email,
password: Faker::Lorem.characters(10)
)
user.skip_confirmation!
user.save!
end
users = User.all
#Create Bookmarks
10.times do
Bookmark.create!(
url: Faker::Internet.url
)
end
bookmarks = Bookmark.all
#Create Topics
10.times do
Topic.create!(
name: Faker::Lorem.sentence
)
end
topics = Topic.all
users.each do |user|
3.times do
user.bookmarks << Bookmark.sample
end
end
topics.each do |topic|
3.times do
user.topics << Topic.sample
end
end
puts "Seed finished"
puts "#{User.count} users created"
puts "#{Bookmark.count} bookmarks created"
puts "#{Topic.count} topics created"
Thanks in advance for your help!
whereever you are calling .sample, the object before it is apparently not the correct type of object. It should either be an array or the 'collection' which results when you query your database. Like this...
posts = Post.all
posts.sample would work correctly
any object which is not an array (or like an array) will not have the 'sample' method available for you to use
You cannot call sample on a class as that is not a valid method. The sample method is used for arrays or ActiveRecord::Relation arrays.
For example, each of these would return a random
[0,1,2,3].sample
(0..10).to_a.sample
Post.all.sample
However, something like these examples would give an error.
User.sample
NoMethodError: undefined method 'sample' for #<Class:0x00000007faa378>
(9..199).sample
NoMethodError: undefined method 'sample' for 9..199:Range

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

Resources