Passing arguments to Faker for my method in Rails? - ruby-on-rails

I have a model called Booking, that should calculate the total from several numbers (amount, deposit, and fee are all added together). I'm having trouble getting these arguments to be seen in Faker.
it "should calculate the total" do
myvar = FactoryGirl.create(:booking, :amount => 900, :deposit => 20, :fee => 8)
myvar.totalamount.should == 928
end
And here's my method:
class Booking < ActiveRecord::Base
validates :to, :from, :amount, presence: true
def totalamount(amount,deposit,fee)
total = (amount + deposit + fee)
return total
end
end
The error message: "wrong number of arguments (0 for 3)"
However, when I do a puts myvar.deposit, it returns the value I gave it - 20.
What am I doing wrong?
Edit: Here is my Factory build for Booking:
FactoryGirl.define do
factory :booking do |b|
b.from { Faker::Lorem.sentence(word_count=3) }
b.to { Faker::Lorem.sentence(word_count=3) }
b.amount { Faker::Number.digit }
end
end

class Booking < ActiveRecord::Base
validates :to, :from, :amount, presence: true
def totalamount
total = (amount + deposit + fee)
return total
end
end
Just had to remove the 3 required attributes after 'totalamount'.

Related

Rails Create new active record with association value passed in params

I have 2 rails models which look like this
class Physician < UserProfile
has_many :state_licenses, inverse_of: :physician, autosave: true, dependent: :destroy
validates :state_licenses, :length => { :minimum => 1, message: "Please select at-least one state license"}
class StateLicense < ApplicationRecord
include RailsAdminPhysicianDependencyConcern
belongs_to :physician, inverse_of: :state_licenses
belongs_to :state, optional: true
attr_accessor :client_id
validates :state, presence: { message: I18n.t("errors.choose_one", field: 'state') }
#validates :license_number, presence: { message: I18n.t("errors.blank") }
def name
return "" unless state
"#{state.try(:name)}"
end
end
In my controller, I am using the code below to create a new Physician record with a bunch of state licenses but for some reason, the state licenses I pass to the create function never make it to the Physician model
def create
physician = nil
ActiveRecord::Base.transaction do
state_licenses = params["state_licenses"]
state_licenses_For_Association = []
if (state_licenses != nil)
state_licenses.each do |state_license|
sl = {}
sl[:state_id] = state_license
state_licenses_For_Association.push(sl)
end
end
physician = Physician.create(params.permit(:first_name, :last_name, :title, :residency_board_status, :residency_specialty_id, :state_licenses => state_licenses_For_Association))
user_record = nil
super do |user|
user_record = user
user.errors.delete(:user_profile)
physician.errors.messages.each { |field, messages| messages.each {|message| user.errors.add(field, message)} }
end
raise ActiveRecord::Rollback unless user_record.persisted? && physician.persisted?
end
AdminNotificationsMailer.physician_signed_up(physician).deliver_now rescue nil
end
What am I doing wrong?
Try changing this:
physician = Physician.create(params.permit(:first_name, :last_name, :title, :residency_board_status, :residency_specialty_id, :state_licenses => state_licenses_For_Association))
to this:
physician = Physician.create(params.permit(:first_name, :last_name, :title, :residency_board_status, :residency_specialty_id).merge(state_licenses: state_licenses_For_Association)) # note the .merge call

Rails SystemStackError: stack level too deep

I am testing my app ( Rails 5) with rspec capybara and factory girl I have the following error...
I am not sure what's happening... I am very new with rspec I hope you could help me :) thank you
Randomized with seed 41137
An error occurred in a `before(:suite)` hook.
Failure/Error: FactoryGirl.lint
SystemStackError:
stack level too deep
You will find my code below:
factories.rb
FactoryGirl.define do
factory :event do
name {Faker::Friends.character}
total_price 50
participant
end
factory :participant do
first_name { Faker::Name.first_name }
salary 900
event
end
end
event.rb
class Event < ApplicationRecord
has_many :participants, inverse_of: :event
validates :participants, presence: true
validates :name, presence: true, length: {minimum: 2}
validates :total_price, presence: true
accepts_nested_attributes_for :participants, reject_if: :all_blank, allow_destroy: true
def total_salary
all_salary = []
participants.each do |participant|
all_salary << participant.salary
end
return #total_salary = all_salary.inject(0,:+)
end
end
event_spec.rb
require 'rails_helper'
describe Event do
it { should have_many(:participants) }
it { should validate_presence_of(:participants) }
it { should validate_presence_of(:name) }
it { should validate_presence_of(:total_price) }
describe "#total_salary" do
it "should return the total salary of the participants" do
partcipant_1 = create(:participant, salary: 2000)
partcipant_2 = create(:participant, salary: 3000)
expect(partcipant_1.salary + partcipant_2.salary).to eq(5000)
end
end
end
edit
In my participant model I had to add optional: true
belongs_to :event, option: true
so fabriciofreitag suggestion works well :)
Let's take a look at your factories:
FactoryGirl.define do
factory :event do
name {Faker::Friends.character}
total_price 50
participant
end
factory :participant do
first_name { Faker::Name.first_name }
salary 900
event
end
end
In this scenario, the creation of event will create a participant, that will create an event, that will create a participant. and so on, in an infinite loop (stack level too deep).
Perhaps you could change it to something like this:
FactoryGirl.define do
factory :event do
name {Faker::Friends.character}
total_price 50
participants { create_list(:participant, 3, event: self) }
end
factory :participant do
first_name { Faker::Name.first_name }
salary 900
end
end

rails 4 refactor factorygirl creates inaccurate data

I have been battling a major refactor to slim down a payments controller and could use a hand. Step one I am trying to fix my factories. Right now all of the factories work great on their own, but when I try to build associations the FactoryGirl.create(:job, :purchased_with_coupon) it will setup the association correctly on the coupon but not the payment. This means that the price paid is always is always 1. I just noticed this which you can see the other section commented out. Before I start tackling the bloated controller I need to figure this out for my tests. Thoughts?
Factories
FactoryGirl.define do
factory :job do
category
company
title { FFaker::Company.position }
location { "#{FFaker::Address.city}, #{FFaker::AddressUS.state}" }
language_list { [FFaker::Lorem.word] }
short_description { FFaker::Lorem.sentence }
description { FFaker::HTMLIpsum.body }
application_process { "Please email #{FFaker::Internet.email} about the position." }
trait :featured do |job|
job.is_featured true
end
trait :reviewed do |job|
job.reviewed_at { Time.now }
end
trait :purchased do |job|
job.reviewed_at { Time.now }
job.start_at { Time.now }
job.end_at { AppConfig.product['settings']['job_active_for_day_num'].day.from_now }
job.paid_at { Time.now }
payments { |j| [j.association(:payment)] }
end
trait :purchased_with_coupon do |job|
job.reviewed_at { Time.now }
job.start_at { Time.now }
job.end_at { AppConfig.product['settings']['job_active_for_day_num'].day.from_now }
job.paid_at { Time.now }
association :coupon, factory: :coupon
payments { |j| [j.association(:payment)] }
end
trait :expired do |job|
start_at = (200..500).to_a.sample.days.ago
job.reviewed_at { start_at }
job.start_at { start_at }
job.end_at { |j| j.start_at + AppConfig.product['settings']['job_active_for_day_num'].days }
job.paid_at { start_at }
payments { |j| [j.association(:payment)] }
end
end
end
FactoryGirl.define do
factory :payment do
job
# price_paid { rand(100..150) }
price_paid { 1 }
stripe_customer_token { (0...50).map { (65 + rand(26)).chr }.join }
end
end
FactoryGirl.define do
factory :coupon do
code { rand(25**10) }
percent_discount { rand(100**1) }
start_at { 2.days.ago }
end_at { 30.day.from_now }
trait :executed do |c|
association :job, factory: [:job, :purchased]
c.executed_at { Time.now }
end
end
end
Models
class Job < ActiveRecord::Base
acts_as_paranoid
strip_attributes
acts_as_taggable
acts_as_taggable_on :languages
belongs_to :company
before_validation :find_company
belongs_to :category
has_one :coupon
has_many :payments
before_create :create_slug, :set_price
after_create :update_vanity_url
accepts_attachments_for :company
accepts_nested_attributes_for :company
accepts_nested_attributes_for :coupon
accepts_nested_attributes_for :payments
validates :title,
:location,
:short_description,
presence: true,
format: { with: /\A[\w\d .,:-#]+\z/, message: :bad_format }
validates :application_process,
presence: true,
format: { with: %r{\A[\w\d .,:/#&=?-]+\z}, message: :bad_format }
validates :title, length: { minimum: 10, maximum: 45 }
validates :location, length: { minimum: 10, maximum: 95 }
validates :short_description, length: { minimum: 10, maximum: 245 }
validates :application_process, length: { minimum: 10, maximum: 95 }
validates :description,
:category_id,
:language_list,
presence: true
validates :reviewed_at,
:start_at,
:end_at,
:paid_at,
date: { allow_blank: true }
validates :start_at, date: { before: :end_at, message: :start_at_before_end_at }, if: proc { start_at? }
validates :end_at, date: { after: :start_at, message: :end_at_after_start_at }, if: proc { end_at? }
scope :active, -> { where.not(reviewed_at: nil, paid_at: nil).where('end_at >= ?', Date.today) }
def expired?
end_at.present? && end_at < Date.today
end
def reviewed?
reviewed_at.present?
end
def paid_for?
reviewed? && paid_at.present?
end
def active?
reviewed? && paid_at.present? && end_at <= Date.today
end
private
def set_price
self.price = AppConfig.product['settings']['job_base_price']
end
def create_slug
self.slug = title.downcase.parameterize
end
def update_vanity_url
self.vanity_url = '/jobs/' + company.slug + '/' + slug + '/' + id.to_s + '/'
save
end
def find_company
existing_company = Company.where(email: company.email) if company
self.company = existing_company.first if existing_company.count > 0
end
end
class Coupon < ActiveRecord::Base
acts_as_paranoid
strip_attributes
belongs_to :job
validates :start_at, date: { before: :end_at }
validates :executed_at, date: { allow_blank: true }
validates_presence_of :job, if: proc { executed_at? }
validates_presence_of :executed_at, if: :job
validates :code,
presence: true,
length: { minimum: 10, maximum: 19 },
uniqueness: { case_sensitive: false },
numericality: { only_integer: true }
validates :percent_discount,
inclusion: { in: 1..100 },
length: { minimum: 1, maximum: 3 },
numericality: { only_integer: true },
presence: true
scope :active, -> { where('start_at < ? AND end_at > ? AND executed_at IS ?', Date.today, Date.today, nil) }
def active?
start_at < Date.today && end_at > Date.today && executed_at.nil?
end
def executed?
job_id.present?
end
end
class Payment < ActiveRecord::Base
belongs_to :job
belongs_to :coupon
validates_presence_of :job
validate :coupon_must_be_active
before_create :net_price
Numeric.include CoreExtensions::Numeric::Percentage
attr_accessor :coupon_code
def coupon_code=(code)
#coupon = Coupon.find_by_code(code)
end
def net_price
return job.price unless #coupon
job.price = #coupon.percent_discount.percent_of(job.price)
self.coupon = #coupon
end
private
def coupon_must_be_active
if #coupon
errors[:coupon] << I18n.t('flash_messages.coupons.id.inactive') unless #coupon.active?
elsif #coupon_code.present?
errors[:coupon_code] << I18n.t('flash_messages.coupons.id.not_found')
end
end
end
It looks like the problem is that there is logic outside of your models that is updating the price_paid column on your Payment, and possibly setting the coupon_id on it as well.
So I would recommend duplicating any extra logic that might be coming from your controllers, service classes, etc. into an after(:create) callback on your factory.
trait :purchased_with_coupon do
# ...other attributes...
association :coupon
after(:create) do |job, evaulator|
discount_value = 100 - job.coupon.percent_discount) / 100.0
calculated_price_paid = job.price * discount_value
create(:payment, price_paid: price_paid, job: job, coupon: coupon)
end
end
Now ultimately, that code belongs in some kind of abstraction, such as a service class that can easily be tested (and used in other tests). However, you mentioned you are getting started on a refactor and want passing tests. I think this is a reasonable compromise until you're ready to abstract it. Ultimately, I would do something like this:
class CreatePaymentWithCoupon
attr_reader :job
def initialize(job)
#job = job
end
def call
job.payments.create(coupon: job.coupon, price_paid: discounted_price)
end
private
def discounted_price
discount_value = (100 - job.coupon.percent_discount) / 100.0
job.price * discount_value
end
end
Then, in your specs:
it "calculates discounted price" do
coupon = create(:coupon, percent_discount: 25)
job = create(:job, :purchased_with_coupon, price: 100)
CreatePaymentWithCoupon.new(job).call
expect(job.payments.first.price_paid).to eq(75.0)
end

uninitialized constant Payroll_Manager::Teachers

I'm making a payroll system for pay salaries. I only need to choice a month, a year and press "create payrolls", and create payrolls for all the teachers
mockup
I created the method "create" in payroll_controller.rb:
Payroll_Manager.new(params[:month], params[:year]).crear_liquidaciones_del_periodo()
The Payroll_Manager is in the file app/helpers/payroll_manager.rb
class Payroll_Manager < PayrollsController
def initialize(month, year)
#month = month
#year = year
end
def crear_liquidaciones_del_periodo
Teachers.each do |t|
t.payrolls.create(#month, #year)
end
end
end
And finally, I have the codel payroll.rb
class Payroll < ActiveRecord::Base
belongs_to :teacher
has_many :payroll_lines
def period
period = month + " " + year
end
validates :month, presence: true
validates :year, presence: true
class Payroll < ActiveRecord::Base
#gross_total, retention_total, neto_total
before_save :calculate_payroll
private
def calculate_payroll
calculate_gross_total
calculate_retention_total
calculate_net_total
end
def calculate_gross_total
self.gross_total = 0
## Concepto.where(type: 1)
haberes = Concepts.all.select{ |c| c.type == 1 }
haberes.each do |h|
parametros_para_linea = {concept_id: h.id, subtotal: h.amount}
self.payroll_line.create(parametros_para_linea)
self.gross_total += h.amount
end
end
def calculate_retention_total
self.retention_total = 0
## Concepto.where(type: 0)
retencion = Concepts.all.select{ |c| c.type == 0 }
retencion.each do |r|
parametros_para_linea = {concept_id: h.id, subtotal: h.amount}
self.payroll_line.create(parametros_para_linea)
self.retention_total += r.amount
end
end
def calculate_net_total
self.net_total = gross_total - retention_total
end
end
end
...When I click the "create payroll" button, I have the error:
uninitialized constant Payroll_Manager::Teachers
enter image description here
Please, help me.
Your class definition in payroll_manager.rb should be PayrollManager, not Payroll_Manager.

Rails models: Validates a number attribute is not eq to zero

I have a column that can be either positive or negative, but never zero. I'm doing the following which doesn't seem to work:
class Transaction < ActiveRecord::Base
validates :amount, presence: true
validates :amount, :numericality => { :not_equal_to => 0 }
.
.
.
This is my test
let(:transaction) { FactoryGirl.build(:transaction) }
it "is invalid if amount is zero" do
transaction.amount = 0
expect(transaction).to have(1).error_on(:amount)
end
This is my factory:
FactoryGirl.define do
factory :transaction do
sequence(:description) { |n| "Transaction #{n}" }
category_id nil
amount -100
notes nil
fund_id 1
end
end
What's the way to check number is either positive or negative? Is there something else I'm doing wrong?
Thanks
You want :other_than, not :not_equal_to
validates :amount, :numericality => { :other_than => 0 }
See the documentation on validates_numericality_of for all the options.

Resources