Hi I run test and it seems he is failing i can't found what is particulary wrong. here is message:
Failure:
ProductsControllerTest#test_can't_delete_product_in_cart [/home/magvin/work/depot/test/controllers/products_controller_test.rb:53]:
"Product.count" didn't change by 0.
Expected: 3
Actual: 2
So he doesn't delete. I looked On model/product.rb,as well everything seems fine as it should be in book
class Product < ApplicationRecord
has_many :line_items
before_destroy :ensure_not_referenced_by_any_line_item
validates :title, :description, :image_url, presence: true
validates :price, numericality: {greater_than_or_equal_to: 0.01, message: "%{value} seems wrong"}
validates :title, uniqueness: true
validates :image_url, allow_blank: true, format: {
with: %r{\.(gif|jpg|png)\z}i,
message: 'must be GIF, JPG or PNG file.'
} #i stands for case insensitive
validates :title, :length => {:minimum => 2}
validates :description, :length => { :in => 3..150 }
#...
#...
private
#ensure that there are no line items referencing this product
def ensure_not_referenced_by_any_line_item
unless line_items.empty?
errors.add(:base, 'Line Items Presents')
throw :abort
end
end
end
Well also i recheked line on test where it's failing,count understand what wrong.
test "can't delete product in cart" do
assert_difference('Product.count', 0) do
delete product_url(products(:two))
end
assert_redirected_to products_url
end
Was fixture problem:) changed and everything works)
Related
My askings_controller.rb is below.
class AskingsController < ApplicationController
before_action :authenticate_user! , only: [:new , :create , :destroy]
def create
#asking=Asking.create(asking_params) do |c|
c.user=current_user
end
if #asking.save
flash[:success] = "依頼に成功しました。"
redirect_to #asking
else
render 'askings/new'
end
end
end
My factories/askings.rb is below.
FactoryGirl.define do
factory :asking do
association :user
sequence(:content){|i| "お願いします#{i}"}
lang "english"
person 'ネイティブ限定'
sex '男性限定'
usepoint 1
finished false
title "MyString"
deadline "2017-1-12"
deadline_time 19
end
end
My askings_contoller_spec.rb is below.
require 'rails_helper'
RSpec.describe AskingsController, type: :controller do
describe 'when login user' do
context 'Post #create' do
before do
#user=create(:user)
login_user(#user)
end
let(:asking_params) {attributes_for(:asking)}
it 'should make askings +1' do
expect{post :create, asking: asking_params}.to change(Asking, :count).by(1)
end
end
end
My model/asking.rb is below.
class Asking < ActiveRecord::Base
belongs_to :user
validates :title , presence: true , length: {maximum: 80}
validates :content , presence: true , length: {maximum: 800}
validates :lang , presence: true
validates :usepoint , presence: true
validates :person , presence: true
validates :sex , presence: true
validates :deadline , presence: true
validates :deadline_time , presence: true
end
Why do I have the error of 'expected #count to have changed by 1, but was changed by 0'?
When I remove 'validates :deadline_time , presence: true' from asking.rb , it works. But I think it isn't wrong.
Please help me.
In factories/askings.rb try to match the format of the deadline_time column. Right now you have the INT 19, perhaps try a string formatted for time (it would be nice to see the schema for Asking) .
Quick edit- My thought is that your factory is not making a valid asking, therefor the count is not increasing.
I got this model:
rails g model Absence user:references company:references from:date to:date date:date category:integer hours:decimal remarks
This also generates:
FactoryGirl.define do
factory :absence do
user nil
company nil
from nil
to nil
date nil
category 0
hours "8.00"
remarks "MyString"
end
end
I set from, to and date to nil because it's either: from and to OR a certain date.
When I try this in my spec:
#absence = create(:absence, user: #company.owner, from: "2015-09-10", to: "2015-09-10", hours: 4)
I receive this error message:
NoMethodError:
undefined method `from=' for #<Absence:0x007f81f5494b88>
What could be wrong?
Edit:
When I remove the
from nil
from the factories/absences.rb I'm getting it on the next field (to) and after removing that I'm seeing the error message on category.
Edit2:
Model:
class Absence < ActiveRecord::Base
belongs_to :user
belongs_to :company
enum type: {holiday: 0, sick: 1}
validates :from, presence: true, if: '!user_id.nil?'
validates :to, presence: true, if: '!user_id.nil?'
validates :date, presence: true, if: '!company_id.nil?'
validates :hours, presence: true, if: '!user_id.nil?'
validates :hours, :numericality => { :greater_than_or_equal_to => 0 }, if: '!user_id.nil?'
validates :category, presence: true, if: '!user_id.nil?'
validates_numericality_of :company_id, allow_nil: true
validates_numericality_of :user_id, allow_nil: true
validate :company_xor_user
validate :to_date_after_from_date
validate :hours_smaller_than_workday
validate :non_overlapping
after_save :calculate_time_checks
after_destroy :calculate_time_checks_delete
DB:
https://www.evernote.com/shard/s29/sh/e8c1429d-9fa7-475b-87e8-3dc11a3f3978/08a7e7d6dfd80c6f407339cab97734c2
FINALLY found the real cause.
At first I had the Absence model created with an attribute named 'type'. This was migrated to both the development and test database. Afterwards I changed it to category and added 'from' and 'to' as well and did a rollback and migrated again (but not on test!).
By using pry
require 'pry'; binding.pry
in the test I did Absence.columns and noticed the difference.
Title pretty much explains the problem.
Here were my validations for my model:
class Lesson < ActiveRecord::Base
belongs_to :school
has_many :users, through: :goals
has_many :goals, dependent: :destroy
validates :school_id, presence: true
validates :date, presence: true, uniqueness: { scope: :school_id }
validates :attendance, numericality: { only_integer: true,
greater_than: 0 },
presence: true, if: :finished?
validates :lesson_plan_week_number, numericality: { only_integer: true,
greater_than: 0 },
presence: true, if: :finished?
end
All of my model tests (aside from the ones dealing with the custom validation) pass with the above code
Then I added validate :motion_presence and the following private method:
def motion_validation
if debate?
errors.add(:motion, "must be present if a debate was held")
else
errors.add(:motion, "cannot be present if a debate was held")
end
end
and now the tests that once passed are failing. What's happening?
Here's the relevant code in the model if I'm organizing it incorrectly
class Lesson < ActiveRecord::Base
belongs_to :school
has_many :users, through: :goals
has_many :goals, dependent: :destroy
validates :school_id, presence: true
validates :date, presence: true, uniqueness: { scope: :school_id }
validates :attendance, numericality: { only_integer: true,
greater_than: 0 },
presence: true, if: :finished?
validates :lesson_plan_week_number, numericality: { only_integer: true,
greater_than: 0 },
presence: true, if: :finished?
validate :motion_presence
private
# Validates the motion depending on debate?
def motion_presence
if debate?
errors.add(:motion, "must be present if a debate was held")
else
errors.add(:motion, "cannot be present if a debate was held")
end
end
end
def motion_presence
if debate?
errors.add(:motion, "must be present if a debate was held")
else
errors.add(:motion, "cannot be present if a debate was held")
end
end
This will always fail because you added to errors in either case.
If you wanted to fail it for multiple conditions, then try doing it in elsif. else means EVERYTHING ELSE and its failing always.
Do it like this:
def motion_presence
if debate?
errors.add(:motion, "must be present if a debate was held")
elsif some_condition
errors.add(:motion, "cannot be present if a debate was held")
end
end
That is because in any case whether debate? returns true or false, it is adding errors to the motion so it will never be successful which results in not saving the lesson object as errors are already added for motion field.
I think you need to add a case where it should just return without adding any errors. Besides just add errors for specific cases
Is there anyway to create a function I can call both in the model and controller? I have a function that grabs an array of files and strips the extension off and want to validate against the list. However I also want access to this list in the controller so I can output a select box for the options. I currently have this, however the VALID_MODULES doesnt get populated all the time.
class Job < ActiveRecord::Base
after_initialize :init
VALID_MODULES =[];
validates :name, presence: true
validates :desc, presence: true
validates :api, presence: true, :inclusion => { :in => VALID_MODULES}
validates :filters, presence: true
validates :toe, presence: true
def init
Dir.foreach('lib/resources') do |item|
next if item == '.' or item == '..' or item == 'resource.rb'
#Wont be called very often so O(n) complexity is fine (small #elements)
VALID_MODULES.push(item[0..-4]) unless VALID_MODULES.include?(item[0..-4])
end
end
end
Instead of using a constant (VALID_MODULES), try making it an attribute of your job.
class Job < ActiveRecord::Base
attr_accessor :valid_modules
after_initialize :init
validates :name, presence: true
validates :desc, presence: true
validates :api, presence: true, :inclusion => { :in => VALID_MODULES}
validates :filters, presence: true
validates :toe, presence: true
def init
#valid_modules ||= []
Dir.foreach('lib/resources') do |item|
next if ['.', '..', 'resource.rb'].include?(item)
#Wont be called very often so O(n) complexity is fine (small #elements)
#valid_modules << item[0..-4] unless #valid_modules.include?(item[0..-4])
end
end
end
Now in your controller you can just call valid_modules on your Job object to return the array.
Example:
job = Job.new
job.valid_modules
# in config/initializers/api_modules.rb
module ApiModules
def self.modules
# the Dir[""] glob syntax here I believe exclude dot directories
# but I still like the Array#include? syntax here for your exclusions list
# you may need to massage the strings of your file list to be more appropriate to your case
#modules ||= Dir["lib/*"].select{|f| !["resource.rb"].include?(f) }
end
end
#app/models/job.rb
validates :api, presence: true, :inclusion => { :in => ApiModules.modules}
Running: Ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-darwin11.2.0], Rails 3.2.0
I'm trying to get elastic search working through the TIRE gem across associations. For some reason I keep getting the following error/errors when performing a rake on a TIRE import or occasionally on a view:
Daves-MacBook-Pro:outdoor dave$ rake environment tire:import CLASS=Gear FORCE=true
[IMPORT] Deleting index 'gears'
[IMPORT] Creating index 'gears' with mapping:
{"gear":{"properties":{}}}
[IMPORT] Starting import for the 'Gear' class
--------------------------------------------------------------------------------
101/101 | 100% rake aborted!######################################
undefined method `last_name' for nil:NilClass
Tasks: TOP => tire:import
Here are my models:
GEAR
class Gear < ActiveRecord::Base
attr_accessible :title, :size, :price, :image_url, :sub_category_id, :user_id
belongs_to :user
belongs_to :sub_category
validates :title, presence: true
validates :size, presence: true
validates :price, presence: true
validates :sub_category_id, presence: true
validates :user_id, presence: true
include Tire::Model::Search
include Tire::Model::Callbacks
def self.search(params)
tire.search(load: true, page: params[:page], per_page: 18) do
query { string params[:query]} if params[:query].present?
end
end
def to_indexed_json
to_json(methods: [:sub_category_name, :user_last_name, :user_first_name, :user_email])
end
def sub_category_name
sub_category.name
end
def user_first_name
user.first_name
end
def user_last_name
user.last_name
end
def user_email
user.email
end
end
USER
class User < ActiveRecord::Base
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation
has_secure_password
has_many :gears
before_save :create_remember_token
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :first_name, presence: true,
length: {:maximum => 50 }
validates :last_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}
def name
first_name + " " + last_name
end
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
Sub_Category
class SubCategory < ActiveRecord::Base
attr_accessible :name
belongs_to :category
has_many :gears
end
What am I missing? Thanks.
I had a few NIL values in my database that was the reason for the errors. Hopefully this can save a few people some time.