I am trying to check if a div has a child with particular class in Capybara, using the following piece of code:
expect(find("#admin-row-1 .glyphicon-ban-circle")).to_not be_empty
Upon debug, I get the following output
(byebug) find("#admin-row-1 .glyphicon-ban-circle")
#<Capybara::Node::Element tag="a" path="/html/body/main/div[2]/div/div/div/table/tbody/tr[3]/td[3]/a[2]">
But still, getting the following expectation error
Failure/Error: expect(find("#admin-row-1 .glyphicon-ban-circle")).to_not be_empty
expected #<Capybara::Node::Element tag="a" path="/html/body/main/div[2]/div/div/div/table/tbody/tr[3]/td[3]/a[2]"> to respond to `empty?`
find returns an element or raises an exception, it doesn't return anything tha responds to empty?, You could use all instead which returns an array like object but a better solution is to use the have_css matcher provided by Capybara
expect(page).to have_css('#admin-row-1 .glyphicon-ban-circle')
Related
Another question for today, but I'm fixing some errors in my extension, and that's the last one.
I had this error many times:
Core: Exception handler (WEB): Uncaught TYPO3 Exception: #145451971: Supplied file object type TYPO3\CMS\Fluid\ViewHelpers\Widget\PaginateViewHelper must be QueryResultInterface
or ObjectStorage or be an array. | UnexpectedValueException thrown in file /var/www/typo3_src_elts/typo3/sysext/fluid/Classes/ViewHelpers/Widget/PaginateViewHelper.php
Maybe I should put a condition when the array is null to display an error message, but where? in controller or template?
If your variable is null, you must define an empty array in the controller befor accessing it with fluid.
If its an array, you can simple add an condition to the template, to check if it's empty:
<f:if condition="{array -> f:count()} > 0">
<f:then><!-- pagination --></f:then>
<f:else><!-- do something when empty --></f:else>
</f:if>
You can also try to check if an variable exist:
<f:if condition="{array}">
<f:then><!-- pagination --></f:then>
<f:else><!-- do something when empty --></f:else>
</f:if>
This should work for null variables, but I dont checked this out.
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
Inside of my Django view I am trying to retrieve results from my database and then pass them on to my template with the following code:
f = request.GET.get('f')
try:
fb_friends_found= UserProfile.objects.filter(facebookid__in=f).values('facebookid')
i = fb_friends_found[0] #To get the dictionary inside of the list
results = i['facebookid'] #To retrieve the value for the 'facebookid' key
variables = RequestContext (request, {'results': results })
return render_to_response('findfriends.html', variables)
I carried out the first three lines within the 'try' block using manage.py shell and this worked fine, printing the correct 'facebookid'.
Unfortunately I can't get it to work in my browser. Any suggestions?
Do you have a specific problem you're running into, such as an exception?
I feel like you should get some kind of exception if you have a try block without an except statement.
try:
# something
except Exception: # but be more specific
print "exception occurred"
Otherwise, the code looks good, and if nothing is rendering in your browser, I'd look into the template. Unless... you're hiding errors in your try block, in which case you should remove the try block and let the error occur to understand what's wrong.