I am converting a Ruby program to Crystal as I learn it.
Here is an error message I am getting:
# Error
Failures:
1) Test Rule class can return the name property
Failure/Error: rule.name.should be "RpsIphone"
Expected: "RpsIphone" (object_id: 4504126256)
got: "RpsIphone" (object_id: 4524981536)
# spec/rule_spec.cr:11
And here is the code that is causing it
# from spec
rule.name.should be "RpsIphone"
I also checked that the two strings when compared with .same? also say they are not the same. I've looked at those 9 characters over and over. What am I missing?
Crystal's .should be tests for the objects being the same,
identical, same object_id
Crystal's .should eq tests for the values being the same
Related
I have a contact number field in my Angular 7 form.I used 'form builder' and 'validators.pattern' for validation.In the HTML, I tried two ways to determine whether there was an error ,but both didnt work.
TypeScript:
mobnumPattern = "^[6-9][0-9]{9}$";
this.myForm = this.formbuilder.group({
contact_no: ['', [Validators.required,Validators.pattern(this.mobnumPattern)]],}
)
1.When I used below HTML, validation always shows true
*ngIf="((myForm.controls['contact_no'].touched) && (myForm.controls['contact_no'].hasError(pattern)))"
2.When I used below HTML, validation always shows false
*ngIf="((myForm.controls['contact_no'].touched) && (myForm.controls['contact_no'].errors.pattern))"
Any idea how to solve this?.
Thanks in Advance.
Lets go over both the cases you have mentioned.
1.When I used below HTML, validation always shows true
I tried recreating the issue in stackblitz but it is always false unlike what you said. Anyway the check myForm.controls['contact_no'].hasError(pattern) returns false since hasError() is expecting a string as its parameter, but pattern here is undefined.
Use this to check if the form control has pattern validation errors.
*ngIf="((myForm.controls['contact_no'].touched)&& myForm.controls['contact_no'].hasError('pattern')))"
2.When I used below HTML, validation always shows false
myForm.controls['contact_no'].errors will be null if the form control does not have any validation errors. So when checking myForm.controls['contact_no'].errors.pattern in the template will throw an error and return undefined. Use a safe navigation operator to protect against a view render failure if the myForm.controls['contact_no'].errors is null.
Like this:
*ngIf="((myForm.controls['contact_no'].touched) && (myForm.controls['contact_no'].errors?.pattern)"
I have made a stackblitz with the above mentioned fix. Check the link to see the working demo.
I am making the first steps with using Django localisation, and I have just faced the first difficulty. I am trying to test that something in models works as expected. For invalid input, a specific ValidationError should occur. The code in the test looks like this:
try:
p = ...
p.full_clean()
self.fail('Expected exception not raised')
except ValidationError as e:
dict_err = dict(e)
self.assertIn('category', dict_err.keys())
self.assertEqual(len(dict_err.keys()), 1, 'Encountered more than one error')
self.assertIn('blank', dict_err['category'][0])
As long as the site operates in English (LANGUAGE_CODE = 'en-uk'), the caught error looks like this:
ValidationError({'category': ['This field cannot be blank.']})
To check that I've got exactly this ValidationError, I am searching for the work 'blank' in the error message (last line of the code above).
It fails as soon as I switch the site to another language. E.g. for German it looks so:
ValidationError({'category': ['Dieses Feld darf nicht leer sein.']})
Looking for 'blank' obviously fails the test. How could I check the error message? I expect, somewhere deep in Django, there should be a unique identifier of this message (so that Django knows how to translate). But I don't see any traces of it in the error value. I would expect something like
self.assertIn(_(id), dict_err['category'][0])
would do the trick, if I could guess what id should be, and if I understand correctly what _() does.
By further trial and error, I've found that for simple messages the message ID is simply the original English message. That is, one can do:
...
expected_error = _("This field cannot be blank.")
self.assertIn(expected_error, dict_err['category'][0])
or even
self.assertEqual(expected_error, dict_err['category'][0])
It works then independent of the site language.
For errors using named-string interpolation, the code would look like follows. Assuming the English-language error message is Value 'x' is not a valid choice., we do:
expected_error = _("Value %(value)r is not a valid choice.") % {'value': 'x'}
self.assertEqual(expected_error, dict_err['category'][0])
I've found that the easiest way to determine the respective message ID is to search for the part of the English error message in the venv files. For example, I found the error above searching for "is not a valid choice", which is obviously an immutable part of the message.
Special thanks to #MosesKoledoye: his comment to my question hinted in the right direction.
I'm using Rails 5 with minitest. How do I properly catch an exception being raised from invoking a controller method? I thought
assert_raises
was the key. However, I have this method
def show
#line = Line.find(params[:id])
end
and although I thought I'm capturing a REcordNotFoundError but writing
# Simple test to verify we get the show page when we
# invoke the page with a valid ID
test "get show page with invalid line id" do
invalid_line_id = -1
assert_raises ActiveRecord::RecordNotFound get line_path(invalid_line_id)
end
and then running it results in a
# Running:
.E
Error:
LinesControllerTest#test_get_show_page_with_invalid_line_id:
ActiveRecord::RecordNotFound: Couldn't find Line with 'onestop_id'=-1
app/controllers/lines_controller.rb:7:in `show'
test/controllers/lines_controller_test.rb:31:in `block in <class:LinesControllerTest>'
error. What's the right way to catch the error in my test?
assert_raises expects a block - you've just called the code.
Try something like:
assert_raises ActiveRecord::RecordNotFound do
get line_path(invalid_line_id)
end
I tried to check the given dictionary is empty or not in robot framework but it is giving an error saying syntax error. Here is the following example of how I compared it:
Run Keyword If '${source_list_data}'=='[]' FAIL and the error which i got is:
Evaluating expression ''[{'data':'value'}]'=='[]'' failed: SyntaxError: invalid syntax (, line 1)
Your syntax works for me. Strange it does not work for you.
Here is another way to achieve it using Get Length:
*** Settings ***
Library Collections
*** Test Cases ***
dict_empty
${source_list_data} = create dictionary
${length} = Get Length ${source_list_data}
Run Keyword If ${length} == 0 log to console Empty Dict
To check if dictionary is empty in robot framework, automatic dictionary variable "&{EMPTY}" can be used:
Run Keyword if ${dict} == &{EMPTY} 'Some Action Keyword'
I am attempting to validate some dates in a Rails 4 application and it's not working.
I looked at lots of similar code samples, like this Same custom validation for several fields in Rails and this http://railscasts.com/episodes/211-validations-in-rails-3. (And others more complicated). I don't understand why my example doesn't work. Trying to find the problem, I've stripped out the actual validation code, and left a stub, because the validation doesn't seem to run and that would seem the base problem (or at least, the first problem).
Here's the code in the validator (which is in app/validators/custom_date_validator.rb
class CustomDateValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
puts "Custom validator was called"
record.errors[attribute] << "Date Not Valid" unless false
end
end
Here's the code from the model:
class CaseInformation < ActiveRecord::Base
include ApplicationHelper
validates :started, :custom_date => true
The error message is:
argument out of range
Extracted source (around line #104):
respond_to do |format|
104 if ( #case_information.update_attributes(params[:case_information]) && #case_information.update_attributes(params[:law_guardians]) )
format.html { redirect_to #case_information, notice: 'Case information was successfully updated.' }
format.json { head :no_content }
The error is (I think) intentional, I put in a date of "1/123/2012", but the validator isn't catching it. Well, actually I stripped out all the validation code and have (I think) the validator writing to the log, as it doesn't seem the validator is even running, at least, there's nothing in the log that shows it ran.
I know that the validator code is being found because in the model, if I change the validation name even a bit I get an error that the validation can't be found.
Really stupid noob question I am sure, your patience is appreciated.
Thanks.
It's indeed failing before your validator gets run-- the "argument out of range" error is what happens when you call Time.parse on a date that can't exist. In irb:
2.0.0p247 :004 > require 'time'
=> true
2.0.0p247 :005 > Time.parse("1/123/2012")
ArgumentError: argument out of range
And I'm betting that started is a datetime or timestamp attribute, right? Rails tries to convert the string from the params hash to their types before any validations are run.