Rspec for presence validation not working in Rails 5 - ruby

Model Todo
class Todo < ApplicationRecord
has_many :items, dependent: :destroy
validates :title, :created_by, presence: true
end
RSpecs
require 'rails_helper'
RSpec.describe Todo, type: :model do
it { should have_many(:items).dependent(:destroy) }
it { should validate_presence_of(:title) }
it { should validate_presence_of(:created_by) }
end
When i run the command bundle exec rspec, i see:
Finished in 1.82 seconds (files took 0.97238 seconds to load)
5 examples, 2 failures
Failed examples:
rspec ./spec/models/todo_spec.rb:8 # Todo should validate that :title cannot be empty/falsy
rspec ./spec/models/todo_spec.rb:9 # Todo should validate that :created_by cannot be empty/falsy
Can anyone explain why is it failing?

This is the issue in shoulda-matchers. You need to add to your spec_helper.rb:
RSpec.configure do |config|
config.include(Shoulda::Matchers::ActiveModel, type: :model)
config.include(Shoulda::Matchers::ActiveRecord, type: :model)
end

Related

Sinatra Upload multiple files with associated model

i'm trying to make a image gallery with sinatra but a thing that should be simple task is confusing and has a lack of doc and tutorial about it!
So please can someone give a light about this?
for upload i'm using shrine
my biggest doubt is related with name params, should use the galleries model or just images?
class Post < ActiveRecord::Base
validates :title, :content, presence: true, on: :create
has_many :galleries, dependent: :destroy
accepts_nested_attributes_for :galleries, allow_destroy: true
end
require_relative "../uploaders/image_uploader"
class Gallery < ActiveRecord::Base
belongs_to :post
validates :image, presence: true, on: :create
include ImageUploader::Attachment.new(:image)
scope :recent, -> { order('created_at desc') }
# validates_size_of :images, maximum: 2.megabyte, message: "Attachment size exceeds the allowable limit (2 MB)."
end
post controller
post "/posts" do
#post = Post.new(params[:post])
#post.user = current_user
#post.image_derivatives! if #post.image_changed? # creates derivatives
if #post.save
# unless params[:galleries].blank?
# params[:galleries]['image'].each do |a|
# #post.galleries.create!(:image => a)
#end
# end
if params[:post][:galleries][:image] && params[:post][:galleries][:image][:filename]
filename = params[:image][:filename]
file = params[:image][:tempfile]
path = "./public/uploads/#{filename}"
# Write file to disk
File.open(path, "wb") { |f| f.write(file.read) }
end
redirect "/posts/#{#post.slug}"
else
#errors = #post.errors
erb :"/posts/new"
end
end

Problems with Factory girl and mongoid

I have this to classes:
class User
...
has_and_belongs_to_many :posts
...
end
class Post
...
has_and_belongs_to_many :users
validates :user_ids, presence: true
...
end
Then I also have this factories:
FactoryGirl.define do
factory :user do
end
end
FactoryGirl.define do
factory :post do
end
end
before I have the validation validates :user_ids, presence: true, it worked well, but when I added that validation, it signals the error in the form so it is good. but rspec doesn't work:
Mongoid::Errors::Validations:
message:
Validation of User failed.
summary:
The following errors were found: Customer ids can't be blank
resolution:
Try persisting the document with valid data or remove the validations.
So I tryed this:
issue on github but for activerecord
blog post
and tried this things:
factory :post do
before_create do |post|
FactoryGirl.build(:user, post: post)
end
end
or
before(:create) do |post|
post.users << FactoryGirl.build(:user, post: post)
end
or
before(:create) do |post|
post.users << FactoryGirl.create(:user, post: post)
end
or
users { create_list(:user, 2) }
or
users { [create(:user, posts: [])] }
but then I get:
bundle exec rspec spec --colour --format documentation
/Users/toni/.rvm/gems/ruby#my-project/bin/ruby_executable_hooks:15: stack level too deep (SystemStackError)

DEPRECATION WARNING: The `Validator#setup` instance method is deprecated and will be removed on Rails 4.2

I don't know what this warning is ? Please suggest something.
Given below is part of my application code.
It gives me error on statement with validates_date line.
Rails suggest me the do something like:
class MyValidator < ActiveModel::Validator
def initialize(options={})
super
options[:class].send :attr_accessor, :custom_attribute
end
end
This is the code of application below:
class Patient < ActiveRecord::Base
searchkick index_name: "patients",text_start: [:first_name,:last_name]
after_update :reindex
has_secure_password
has_many :addresses
has_many :vitals
has_attached_file :avatar, :styles => { :medium => "150x150>", :thumb => "50x50>" }, :default_url => "app/assets/images/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
validates :email, email_format: {message: "Invalid email format" }
validates_uniqueness_of :email
validates :password_digest, presence: true, confirmation: true, length: {minimum: 8,message:"Must be of atleast 8 characters"}
validates :first_name, presence: true, format: { with: /\A[a-zA-Z]+\z/, message: "First Name should contain only alphabets"}
validates :last_name, presence: true, format: { with: /\A[a-zA-Z]+\z/, message: "Last Name should contain only alphabets" }
validates_date :dob,:before => lambda { Date.current }, presence: true
validates :password_digest, presence: true, confirmation: true, length: {minimum: 8,message:"Must be of atleast 8 characters"}
validates :primary_phone_no, presence: true,numericality: {only_integer: true}
end
You don't need to worry right now. I see from validates_date you are using the validates_timeliness gem - it's that gem that is currently throwing the deprecation warning.
It is an open issue on that gem and it's being worked on - this is the current open issue: https://github.com/adzap/validates_timeliness/pull/114
I suggest you just wait until they fix it and then update the gem. It's just a warning and won't stop anything working right now.

Rails 3.2.9.Testing observer with RSpec(trouble with should_receive)

I have such problem. My test checks whether the Observer called, but does not execute it.
My files:
todo_observer.rb:
class TodoObserver < ActiveRecord::Observer
def after_create(todo)
todo.add_log('creating')
end
end
todo.rb:
class Todo < ActiveRecord::Base
attr_accessible :content, :done, :order
validates :content, :presence => true,
:length => {:minimum => 2}
def add_log(event)
Logdata.start_logging(self.content, event)
end
end
logdata.rb
class Logdata < ActiveRecord::Base
attr_accessible :modification, :event
def self.start_logging(content, event)
Logdata.create!(:modification => content, :event => event)
end
end
todo_observer_spec.rb:
require 'spec_helper'
describe TodoObserver do
before(:each) do
#attr = { :modification => "Example", :event => 'Event' }
#attr_todo = { :content => "Example", :done => :false }
end
describe 'after_create' do
it "should create log about creating task" do
count_log = Logdata.all.size
todo = Todo.new(#attr_todo)
todo.should_receive(:add_log).with('creating')
todo.save!
(Logdata.all.size).should eq(count_log + 1)
end
end
end
When I run test I get such error
Failure/Error: (Logdata.all.size).should eq(count_log + 1)
expected: 1
got: 0
Its mean, that observer called,but doesn't create instance of Logdata. When I comment string(check the call)
todo.should_receive(:add_log).with('creating')
My tests were successful.And accordingly its success when I comment string (Logdata.all.size).should eq(count_log + 1)and uncomment previous string.
How does the function should_receive to create an instance of the class Logdata?
should_receive prevents the actual method from being called.
You should create two separate tests. One to check that the log is added to the todo, and one to check that the log is created.
describe 'after_create' do
it "should add a log to the todo" do
todo = Todo.new(#attr_todo)
todo.should_receive(:add_log).with('creating')
todo.save!
end
it "should create a new logdata" do
todo = Todo.new(#attr_todo)
expect {
todo.save!
}.to change {Logdata.count}.by(1)
end
end

RSpec : undefined method `name' for nil:NilClass

I am getting this error while following the tutorial from railstutorial.org.
Model class : $APPLICATION_HOME/app/models/user.rb
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
#validations
validates :name, presence: true, length: { maximum: 50}
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 }
validates :password, length: { minimum: 6 }
end
View page : $APPLICATION_HOME/app/views/show.html.erb file
<% provide :title, #user.name %>
<h1><%= #user.name %></h1>
RSpec file : $APPLICATION_HOME/app/spec/requests/user_pages_spec.rb
require 'spec_helper'
describe "UserPages" do
subject { page }
describe "signup page" do
before { visit signup_path }
it { should have_selector('h1', text: "Sign up") }
it { should have_selector('title', text: full_title('Sign up')) }
end
describe "profile page" do
let(:user) { FactoryGirl.create(:user) }
before { visit user_path(user) }
it { should have_selector('h1', text: user.name) }
it { should have_selector('title', text: user.name) }
end
end
Here is factories.rb which I have put in $APPLICATION_HOME/spec/factories.rb
FactoryGirl.define do
factory :user do
name "amit"
email "amit#gmail.com"
password "foobar"
end
end
A snapshot of Gemfile
group :test do
gem 'capybara', '1.1.2'
gem 'factory_girl_rails'
end
Here is log I am getting while testing the spec.
Failures:
1) UserPages profile page
Failure/Error: before { visit user_path(user) }
ActionView::Template::Error:
undefined method `name' for nil:NilClass
# ./app/views/users/show.html.erb:1:in `_app_views_users_show_html_erb__369651065_78543920'
# ./spec/requests/user_pages_spec.rb:18:in `block (3 levels) in <top (required)>'
2) UserPages profile page
Failure/Error: before { visit user_path(user) }
ActionView::Template::Error:
undefined method `name' for nil:NilClass
# ./app/views/users/show.html.erb:1:in `_app_views_users_show_html_erb__369651065_78543920'
# ./spec/requests/user_pages_spec.rb:18:in `block (3 levels) in <top (required)>'
Finished in 0.68212 seconds
12 examples, 2 failures
The error comes at these two lines
it { should have_selector('h1', text: user.name) }
it { should have_selector('title', text: user.name) }
Please help me to resolve these errors.
Thanks, Amit Patel
It was typo in $APPLICATION_HOME/app/controllers/users_controller.rb
def show
#users = User.find(params[:id])
end
If you notice, the instance variable name is pluralized (#users) and I have used singular name (#user) in the erb template. That is why it is getting failed.

Categories

Resources