RSpec Model Testing: Failures - ruby-on-rails-4

I am teaching myself RSpec (v3.1.7). I have installed rspec with rails g rspec:install into an existing rails app - freshly created.
I created a model: rails g rspec:model zombie. Ran the migration and all went well.
In: app/models/zombie.rb:
class Zombie < ActiveRecord::Base
validates :name, presence: true
end
In: app/spec/models/zombie_spec.rb:
require 'rails_helper'
RSpec.describe Zombie, :type => :model do
it 'is invalid without a name' do
zombie = Zombie.new
zombie.should_not be_valid
end
end
In terminal when I ran (in the app dir): rspec spec/models I get:
F
Failures:
1) Zombie is invalid without a name
Failure/Error: zombie.should_not be_valid
NoMethodError:
undefined method `name' for #<Zombie id: nil, created_at: nil, updated_at: nil>
# ./spec/models/zombie_spec.rb:6:in `block (2 levels) in <top (required)>'
Im following a video tutorial and I followed the video (Testing with RSpec) down to the latter. I'm like losing weight on the 2nd chapter. Am I missing something? Is the video using an older version of rspec for their video tutorial?
In my migration file:
class CreateZombies < ActiveRecord::Migration
def change
create_table :zombies do |t|
t.timestamps
end
end
end

Your model don't know what name is since you did not define the attribute in your migration:
class CreateZombies < ActiveRecord::Migration
def change
create_table :zombies do |t|
t.string :name
t.timestamps
end
end
end
Then run:
rake db:migrate
Then this should work fine:
z = Zombie.new(name: 'foo')
z.name
=> 'foo'

I think you are missing the name attribute. The following migration file will add name attribute to zombie model:
class AddNameToZombies < ActiveRecord::Migration
def change
add_column :zombies, :name, :string
end
end
finally run the following commands:
rake db:migrate
rake db:test:prepare
and that's it

Related

NoMethodError name RoR user.name

Followed the tutorial at SitePoint
for a simple sorcery app. I am receiving undefined method `name' for nil:NilClass
migration
class SorceryCore < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email, :null => false
t.string :crypted_password
t.string :salt
t.timestamps :null => false
end
add_index :users, :email, unique: true
end
end
/home/david/Magical/app/views/user_mailer/activation_needed_email.html.erb
<p>Welcome, <%= #user.name %>!</p>
<p>To login to the site, just follow <%= link_to 'this link',
activate_user_url$
<p>Thanks for joining and have a great day!</p>
users.rb
class User < ActiveRecord::Base
authenticates_with_sorcery!
validates :password, length: { minimum: 3 }
validates :password, confirmation: true
validates :email, uniqueness: true, email_format: { message: 'has
invalid format'
End
I took the long way home and cloned the Github repo. At first I was getting a 'stack level too deep' error, but I found that the gemfile loaded rails 4.2.1 .
I changed this to 4.2.10 and all went well after the migrations and minor tweaks in the tutorial.
along the way, I found rails_db gem which is a great simple gem for working with sqLite. rails_db gem

Paperclip giving NameError: uninitialized constant Model::ImageUploader

I Have found a similar question:
NameError: uninitialized constant Article::ImageUploader when using Carrierwave on rails 4.1.5
But I have tried the suggestions there:
carrierwave is installed and bundle is complete
And I have double checked my models.
My user model has:
has_one :image, :as => :assetable, :class_name => "User::Image", :dependent => :destroy
And my user creation works find but as soon as I try to access the views it breaks by this code:
<%= link_to image_tag((current_user.image.nil? ? Settings.default_user_image : current_user.image.attachment.url(:thumbnail)) , :style=>'max-width:60px;', :alt=>current_user.full_name, :title=>current_user.full_name), user_path(current_user) %>
I am not sure why this broke, earlier it was working fine, only thing I can think of is, I did bundle once again when my gemfile.lock got conflicts.
This is how I replicate the issue on rails console:
2.1.1 :001 > u = User.new
2.1.1 :002 > u.build_image
NameError: uninitialized constant User::User::Image
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/inheritance.rb:133:in `compute_type'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/reflection.rb:190:in `klass'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/reflection.rb:207:in `build_association'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/associations/association.rb:247:in `build_record'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/associations/singular_association.rb:29:in `build'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.0/lib/active_record/associations/builder/singular_association.rb:18:in `build_image'
from (irb):2
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/railties-4.1.0/lib/rails/commands/console.rb:90:in `start'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/railties-4.1.0/lib/rails/commands/console.rb:9:in `start'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:69:in `console'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
from /home/aditya/.rvm/gems/ruby-2.1.1/gems/railties-4.1.0/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
Please help. I am stuck at a critical point right now.
Path to the file where error is happening is:
/demo/app/views/home/index.html.erb
Image class resides in:
/demo/app/models/user/image.rb
Contents for image.rb
class User::Image < Asset
has_attached_file :attachment, {
fog_credentials: {:aws_access_key_id=>"***", :aws_secret_access_key=>"***", :provider=>"AWS"}, :fog_public=>true, :fog_directory=>"test",
styles: { :thumbnail => "60x60#", :profile => "165x165#" },
storage: :multiple,
path: ":compatible_rails_root/users/files/:id/:style.:extension",
url: "/uploads/posts/files/:id/:style.:extension",
multiple_if: lambda { |user| true },
display_from_s3: lambda { |user| true }
}
validates_attachment_content_type :attachment, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end
User mode is simply in
/demo/app/models
Probably, your namespaces are wrong, try to write your classes as follows (note the introduced Users module):
# app/models/users/image.rb
module Users
class Image < Asset
has_attached_file :attachment, { # ...
# ....
end
end
and just modify a line referring to the Image class in User class (the only change is that it's Users::Image now:
# app/models/users.rb
class User < ActiveRecord::Base
has_one :image, :as => :assetable, :class_name => "Users::Image", #...
# ...
end
this (and maybe one restart of the server later) and everything should be fine.

add_index :name, :email:, unique: true not working for me

I seen this question before on here but the solution on there is not working for me. Rake Aborted , on add_index(:users, :email, {:unique=>true})
In the Rails Tutorial by Michael Hartl he wants you to add_index :name, :email, unique: true I keep getting this error message.
$ bin/rake db:migrate RAILS_ENV=test
DL is deprecated, please use Fiddle
== 20141224060705 AddIndexToUsers: migrating ==================================
-- add_index(:users, :email, {:unique=>true})
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::ConstraintException: indexed columns are not unique: CREATE UNIQUE INDE
X "index_users_on_email" ON "users" ("email")c:/Sites/example/db/migrate/2014122
4060705_add_index_to_users.rb:3:in `change'
c:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
there are no users in the database. here is a picture of the database
You have to enclose the attributes you want to add the index into an array like so:
add_index :users, [:name, :email], unique: true
The first argument is the table name, the second can be an array of attributes or a single attribute, and then some options.
Hope this helps!

undefined method `attr_accessible' with Mongoid

I am using Rails 4.1.1, ruby 2.1, mongodb, mongoid as a wrapper, rails_admin for creating admin interfaces
I know that 'attr_accessible' no longer works for Rails4. So i have installed 'protected_attributes' gem. But still no success i am still getting warning in my console
[RailsAdmin] Could not load model Company, assuming model is non existing. (undefined method `attr_accessible' for Company:Class)
So, rails admin do not load the class Company because i have defined attr_accessible in the model. Here is my company model.
class Company
include Mongoid::Document
##employees_strength = {0 => '0-10', 1 => '11-50', 2 => '51-100', 3 => '101-500', 4 => '501-1000', 5 => '1000+', 6 => '5000+'}
field :name, type: String
field :website, type: String
field :domain_name, type: String
field :strength, type: Integer
has_many :employees
has_one :admin, :class_name => 'Employee', :dependent => :destroy, :inverse_of => :organization
#attr_accessible :name, :website, :domain_name, :strength#, :admin_attributes, :allow_destroy => true
attr_accessible :admin_attributes
accepts_nested_attributes_for :admin, :allow_destroy => true
end
Please any can body can help?
Thanks
Mongoid 4 (<= 4.0.2 at the time of writing) does not know about the ActiveModel::MassAssignmentSecurity module provided by protected_attributes gem.
As such you must include the behaviour in your models manually e.g.
class SomeDocument
include Mongoid::Document
include ActiveModel::MassAssignmentSecurity
field :some_field
attr_accessible :some_field
end
However, this gets tedious pretty quickly so a reasonable alternative is to include the module into the Mongoid::Document module before any of your models are defined.
module Mongoid
module Document
include ActiveModel::MassAssignmentSecurity
end
end

RubyMine Rails console create error

I'm currently working on a Ruby on Rails application using RubyMine 5.4.3.2.1. I'm using Rails 4 and Ruby 1.9.3p429. In my application, I have a class file 'user.rb' with the following code:
class User < ActiveRecord::Base
validates :first_name, presence: true
validates :last_name, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness:{case_sensitive: false }
validates :password, length: { minimum: 6}
has_secure_password
before_save { self.email = email.downcase }
end
and a related migration file '[timestamp]_create_users.rb' with the following:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :email
t.string :password_digest
t.timestamps
end
end
end
Using the RubyMines Run Rake Task, I ran a db:migration to create the users table. The problem is that RubyMines doesn't accept any User.create command to enter data into the database. E.g
User.create (first_name:"John",last_name:"Doe",email:"jdoe#example.com",password:"testing",password_confirmation:"testing")
The error it gives is
SyntaxError: (irb):1: syntax error, unexpected tLABEL
User.create (first_name:"John",last_name:"Doe",ema...
^
(irb):1: syntax error, unexpected ',', expecting $end
...er.create (first_name:"John",last_name:"Doe",email:"jdoe#...
^
This works fine when I run it in my command prompt using the 'rails console', but it gets tedious to repeatedly refer to the command prompt. I've tried running the Rails Console in RubyMine in both default and development, with neither yielding a positive result. Can anyone tell me what I'm doing wrong and how to resolve this?
remove the space between User.create and the left parenthesis User.create(...) instead of User.create (...)
Cheers