Date.today.to_s(:long) not converting to string - ruby-on-rails

I am working on an assignment and I have written the following method based on our instructions:
def create_todolist(params)
due_date = Date.today.to_s(:long)
TodoList.create(list_name: params[:name],list_due_date: params[:due_date])
end
But when I run the rspec test, I get the following error:
1) Assignment rq03 rq03.2 assignment code has create_todolist method should create_todolist with provided parameters
Failure/Error: expect(testList.list_due_date).to eq due_date
expected: Thu, 07 May 2020
got: "2020-05-07"
(compared using ==)
Diff:
## -1,2 +1,2 ##
-Thu, 07 May 2020
+"2020-05-07"
# ./spec/assignment_spec.rb:177:in `block (4 levels) in <top (required)>'
# ./spec/assignment_spec.rb:14:in `block (2 levels) in <top (required)>'
Here is the rspec test:
context "rq03.2 assignment code has create_todolist method" do
it { is_expected.to respond_to(:create_todolist) }
it "should create_todolist with provided parameters" do
expect(TodoList.find_by list_name: "mylist").to be_nil
due_date=Date.today
assignment.create_todolist(:name=> 'mylist', :due_date=>due_date)
testList = TodoList.find_by list_name: 'mylist'
expect(testList.id).not_to be_nil
expect(testList.list_name).to eq "mylist"
expect(testList.list_due_date).to eq due_date
expect(testList.created_at).not_to be_nil
expect(testList.updated_at).not_to be_nil
end
end
At first I had just due_date = Date.today and was getting the same error and I'm not sure how to fix it. I'm wondering if it is because I am using a different version of ruby/rails than what was used when the course was created ( 5 years ago -_-).
Any help would be greatly appreciated!
Thank you :)

You are trying to compare a Date object:
due_date = Date.today
With a string object you generated while you created your record:
Date.today.to_s(:long)
As you can see, these are different types of objects:
Date.today.to_s(:long)
=> "May 07, 2020"
Date.today.to_s(:long).class
=> String
Date.today
=> 2020-05-07
Date.today.class
=> Date
Date.today.to_s(:long) == Date.today
=> false

I figured it out. When I was creating the TodoLists table, I didn't specify the migration type as :date. so by default, due_date was set to be a string. So I set to type :date and changed due_date to equal:
due_date = Date.today
Thank you for taking the time to help me out :)

Related

Rspec, fail testing date

I'm trying to test this :
it "should calculate the max_validation_deadline" do
tasting = Tasting.create!(valid_attributes)
expect ( tasting.max_validation_deadline.to_s ).to eq(today_plus_one.to_s)
end
But it fails. When I'm debugging it I'm having this.
(byebug) tasting.max_validation_deadline.to_s
"2016-12-13 01:00:00 UTC"
(byebug) today_plus_one.to_s
"2016-12-13 01:00:00 UTC"
(byebug) expect ( tasting.max_validation_deadline.to_s ).to eq(today_plus_one.to_s)
*** ArgumentError Exception: bad value for range
Why does it fail saying bad value for range as I'm passing two strings ?
Edit
Here is a full byebug when I'm not testing with to_s.
bundle exec rspec spec/models/tasting_spec.rb
........
[76, 85] in server/spec/models/tasting_spec.rb
76: end
77:
78: it "should calculate the max_validation_deadline" do
79: tasting = Tasting.create!(valid_attributes)
80: byebug
=> 81: expect ( tasting.max_validation_deadline ).to eq(today_plus_one)
82: end
83:
84: it "should calculate the current_opened_places" do
85: tasting = Tasting.create!(valid_attributes)
(byebug) expect ( tasting.max_validation_deadline ).to eq(today_plus_one)
*** NoMethodError Exception: undefined method `to' for Tue, 13 Dec 2016 01:00:00 UTC +00:00:Time
nil
(byebug)
It's a formatting error.
Replace...
expect ( tasting.max_validation_deadline ).to eq(today_plus_one)
with...
expect( tasting.max_validation_deadline ).to eq(today_plus_one)
In the first method, the (expression).to is the passed parameter, when it should be just (expression)
You can demonstrate this problem easily...
expect ("hello").to eq("hello")
generates "bad value for range"
expect("hello").to eq("hello")
is fine.

rspec - why does this assert_equal comparison test work on a mac and not on Ubuntu? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
rspec - why does this attribute comparison usng assert_equal fail when they are the same, on ubuntu only?
Ruby: 1.9.3-p194
Rails: 3.2.8
Ubuntu: 12.04
The test has a lot of setup and then eventually does:
assert_equal #iep_service.attributes, IepService.first.attributes
Works on a mac but fails on ubuntu with:
2) Iep Service Spreadsheet A typical district With pre-existing students And a pre-existing Iep Service for one of those students And an Iep S[52/427$
SV Prevent importing
Failure/Error: assert_equal #iep_service.attributes, IepService.first.attributes
MiniTest::Assertion:
<{"id"=>212,
"duration"=>30,
"frequency"=>3,
"period"=>"week",
"group_size"=>"group",
"location"=>nil,
"service"=>nil,
"area_of_need"=>"speech",
"created_at"=>Wed, 24 Oct 2012 18:59:47 UTC +00:00,
"updated_at"=>Wed, 24 Oct 2012 18:59:47 UTC +00:00,
"therapist_id"=>nil,
"start_date"=>nil,
"end_date"=>nil,
"student_id"=>233,
"adhoc"=>false}> expected but was
<{"id"=>212,
"duration"=>30,
"frequency"=>3,
"period"=>"week",
"group_size"=>"group",
"location"=>nil,
"service"=>nil,
"area_of_need"=>"speech",
"created_at"=>Wed, 24 Oct 2012 18:59:47 UTC +00:00,
"updated_at"=>Wed, 24 Oct 2012 18:59:47 UTC +00:00,
"therapist_id"=>nil,
"start_date"=>nil,
"end_date"=>nil,
"student_id"=>233,
"adhoc"=>false}>.
# (eval):2:in `assert_equal'
# ./spec/models/iep_service_spreadsheet_spec.rb:71:in `block (6 levels) in <top (required)>'
The full source, if it help, is:
context "A typical district" do
before(:each) { set_up_district }
context "With pre-existing students" do
before(:each) { StudentSpreadsheet.new(#district, open_spec_fixture_file('sample-students.csv')) }
context "And a pre-existing Iep Service for one of those students" do
before(:each) { #iep_service = FactoryGirl.create(:iep_service, :student => #district.students.first) }
context "And an Iep Service CSV" do
before(:each) { #spreadsheet = IepServiceSpreadsheet.new(#district, open_spec_fixture_file('sample-ieps.c sv')) }
specify "Prevent importing" do
# Leave database untouched
assert_equal 1, IepService.count
assert_equal #iep_service.attributes, IepService.first.attributes
# Provide error report
assert #spreadsheet.error_report.any?
end
end
end
end
end
assert_equal uses the operator/method ==.
You can read the documentation for assert_equal here: http://ruby-doc.org/core/classes/Test/Unit/Assertions.html#M006665. It comes directly from Ruby, Rails don't overrides the definition.
So depending on the object type the == bahaves differently, and also as it comes from Ruby there may be a different implementation or slightly difference in the ruby code.
Anyways, it is better for you to compare value by value or live with the == comparison may bring to you.

Rails time formatting test failing because it's one hour off?

I have the following method in one of my Rails classes:
def human_departure_time
"#{departure_time.strftime("%A, %d %B %Y")} at #{departure_time.strftime("%I:%M %p")}"
end
As you can see, it just takes a datetime attribute of the model and formats it so that it is more human friendly.
Anyway, I have the following test for this method:
describe "human_departure_time" do
it "should output the time in readable format" do
# first I use the Timecop gem to freeze the time
Timecop.freeze(DateTime.now) do
bus_time = DateTime.now + 1.days
# factory a bus with a specific departure time
bus = Factory :bus, departure_time: bus_time
expected = "#{bus_time.strftime("%A, %d %B %Y")} at #{bus_time.strftime("%I:%M %p")}"
# check that the output is as expected
bus.human_departure_time.should == expected
end
end
end
Pretty simple but the test fails by one hour with the following output:
Failures:
1) Bus human_departure_time should output the time in readable format
Failure/Error: bus.human_departure_time.should == expected
expected: "Wednesday, 17 August 2011 at 03:13 AM"
got: "Wednesday, 17 August 2011 at 02:13 AM" (using ==)
# ./spec/models/bus_spec.rb:34:in `block (4 levels) in <top (required)>'
# ./spec/models/bus_spec.rb:30:in `block (3 levels) in <top (required)>'
Here is my bus factory just incase that is important. I'm overwriting the departure time with the frozen time plus one hour in my test.
factory :bus do
origin_name "Drogheda"
event_name "EP"
departure_time { DateTime.now + 14.days }
end
I assume this is something to do with daylight savings time or something? How can I fix this issue?
ActiveRecord could be automatically converting time attributes in your model to local time.
You can try and use the %Z parameter of strftime to see the time zone of the outputted timestamp to see where a possible conversion is sneaking into your time.
Some Googled hints that might be relevant:
default_timezone:
http://apidock.com/rails/ActiveRecord/Base/default_timezone/class
ActiveRecord::Base.time_zone_aware_attributes
config.active_record.time_zone_aware_attributes:
http://tamersalama.com/2011/01/10/rails-disable-timezone-conversions/
https://mirrors.kilnhg.com/Repo/Mirrors/From-Git/Rails/History/70cb470c1ab8
http://www.ruby-forum.com/topic/2096919
http://www.ruby-forum.com/topic/890711

Tests are not passing

I'm using RSpec for tests and I don't know how to get this to green.
In this case, I have a model called "PartType" that holds an attribute called "quotation".
The value for quotation comes from a form, so it will be a string.
To demonstrate you can go to console and type:
(1..1000).includes?("50") # false
but..
(1..1000).includes?(50) # true
And this value can have decimals. So I needed to do a "type_cast".
I have this on my PartTypemodel:
before_validation :fix_quotation, :if => :quotation_changed?
protected
def fix_quotation
self[:quotation] = quotation_before_type_cast.tr(' $, ' , '.' )
end
This are working as expected BUT when go to tests, it fails.
Here is my part_type_spec.rb:
require 'spec_helper'
describe PartType do
before(:each) do
#attr = { :title => "Silver", :quotation => 100 }
end
it "should create a instance given a valid attributes" do
PartType.create!(#attr)
end
it "should accept null value for quotation" do
PartType.new(#attr.merge(:quotation => nil)).should be_valid
end
it "should accept 0 value for quotation" do
PartType.new(#attr.merge(:quotation => 0)).should be_valid
end
end
And finally the failing tests:
Failures:
1) PartType should create a instance given a valid attributes
Failure/Error: PartType.create!(#attr)
NoMethodError:
undefined method tr' for 100:Fixnum
# ./app/models/part_type.rb:7:infix_quotation'
# ./spec/models/part_type_spec.rb:10:in `block (2 levels) in '
2) PartType should accept 0 value for quotation
Failure/Error: PartType.new(#attr.merge(:quotation => 0)).should be_valid
NoMethodError:
undefined method tr' for 0:Fixnum
# ./app/models/part_type.rb:7:infix_quotation'
# ./spec/models/part_type_spec.rb:18:in `block (2 levels) in '
Finished in 0.06089 seconds
3 examples, 2 failures
Your include? snippets are wrong, I got false in the first, true in the second.
before_validation is executed and quotation_before_type_cast is expected to be a String but it is a Fixnum. Change 100 to '100' and 0 to '0'.

I am not able to subtract two dates from each other using Ruby...why?

this is the code I have. It is a method for a contact.rb (Contact is a model):
def event_delay event
# find instance of contact_event
puts "+++++++++++++++inside event_delay method"
event_class = event.class.name
event_id = event_class.foreign_key.to_sym
#puts event_id
contact_event_class = "Contact#{event_class}".constantize
#puts contact_event_class
contact_event = contact_event_class.first(:conditions =>
{:contact_id => self.id,
event_id => event.id})
#puts "inspect contact_event"
#puts contact_event.inspect
if !contact_event.nil?
puts "---- #{contact_event.title} not nill"
puts contact_event.id
date_sent = contact_event.date_sent
target_send_date = self.date_entered + event.days
puts "date_sent:"
puts date_sent.to_date
puts "target send date:"
puts target_send_date
return date_sent - target_send_date
end
end
The goal is to return the difference in days between the time a date_sent to the time target_send_date. But I get the following error:
undefined method `-#' for Sun, 08 Aug 2010:Date
Maybe both values are not dates? The - method is defined so that's why I'm thinking that you might not have two dates. Does this work in irb for you?
irb(main):001:0> require "date"
=> true
irb(main):002:0> Date.new(2010, 10, 20) - Date.new(2010, 9, 20)
=> Rational(30, 1)
irb(main):003:0>
After migrating to Rails 3.2, I got the same strange error when running specs, but was able to isolate it:
3.days.ago - Date.today
=> NoMethodError: undefined method `-#' for Sun, 29 Apr 2012:Date
'3.days.ago' produces an ActiveSupport::TimeWithZone object, which (apparently) does not mix with the Date object that Date.today gives you.

Resources