$.ajax request breaking js: true spec in rspec - ruby-on-rails

I have a spec that passes looking like the following:
scenario "Brand likes a comment", js: true do
visit post_path(question, as: brand)
within("#comment_#{comment.id}") do
click_on "Like"
end
expect(page).to have_text "Like •1"
end
I've recently added a page with chart.js graph and I am loading the data for that graph with an ajax request that looks as so:
$.ajax({
url: "/admin/reporting/weekly_new_users",
type: "get",
dataType: "json",
cache: false,
success: function(response){
var ctx = document.getElementById("weeklyUsers");
new Chart(ctx, {
type: 'line',
data: {
labels: response.weekly_users.map(arr => arr[0]),
datasets: [{
label: '# of New Users',
data: response.weekly_users.map(arr => arr[1]),
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
],
borderWidth: 1
}]
},
});
}
})
};
This ajax request is causing my spec with js:true to fail, with the following error message:
Failure/Error: raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"
ActionController::RoutingError:
No route matches [GET] "/likes/1"
When I comment out the ajax request the spec passes. Not sure whats causing this, any ideas?

You've indicated you're using capybara-webkit as your driver for JS tests - If that's actually true, then most likely you're not fully polyfilling and transpiling your JS code to be compatible with it. This ends up meaning you have errors (unsupported JS) in the concatenated assets served to your app which prevents some of the JS from being processed. In this case I'm guessing your Like link/button is normally processed by JS (possibly you've set a method on the link for Rails to use - POST, PUT, PATCH etc) but the errors in the JS are preventing the JS handlers from being attached to the link/button.
As for what in your $.ajax is causing issues, one possibility is that you're using arrow functions which are not supported by capybara-webkit (it's roughly equivalent to a 6-7 year old version of Safari). In order to continue using capybara-webkit you need to make sure all of your JS is transpiled and polyfilled to be compatible with really old browsers. A MUCH better solution, although possibly more work, is to swap over to using Selenium with headless Chrome or Firefox for your testing. Not only do you get the ability to test on modern browsers your users are actually using, but also the ability to easily swap between headed and headless when trying to debug issues.

Related

POST request done with Authenticity Token, but exception still rased

My controller is responding to a js GET request, and in my js.erb file I am reporting back with the Fingerprint2 generated browser data of the users browser. This is done with a POST request, because of the large data string, so I have inserted a beforeSend method that adds the Authenticity Token.
However, this is rejected with ActionController::InvalidAuthenticityToken - ActionController::InvalidAuthenticityToken. When I check, the header looks like it does in the GET requests that succeed:
X-CSRF-Token:hl/TgkY7k0yBG03KX9IBrsDhk2K4tUUh8JTooT7A0yYZ0l53p8lTt0F3dZvRwyS3bIkbbkuTdElP2KisozjXjw==
The js code looks like this:
(new Fingerprint2).get(function(fingerprint, components) {
return $.ajax({
url: "/user_browser",
type: "post",
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token',
$('meta[name="csrf-token"]').attr('content'))
},
data: {
some_id: '123',
components: JSON.stringify(components),
fingerprint: fingerprint
},
dataType: "json"
}).success(function(data) {});
});
I found the root of the problem. Some days ago I changed my config/session_store.rb from:
MyApp::Application.config.session_store :cookie_store, key: '_my-app_session'
to:
MyApp::Application.config.session_store :disabled
When I changed this back the problem disappeared.

Why is Mandrill-api for Node expecting multiple callbacks

This question is mainly addressed to the creators of Mandrill, but anyone who have something to add are of course free to answer!
Why are the mandrill-api expecting two callbacks in the send messages functions? One to handle the result, and a second one to handle errors. I don't know all that much about other programming language, but I do know that in NodeJs there is a wide spread convention of using one callback, with 2 (sometimes more...) parameters. The first parameter is the error (null if non-existent), and the second parameter is the result.
I agree with you completely, Anders!
When I started using this node API, I got a bit fed up with just that. For one thing.
I cloned the latest version (at the time 1.0.39, now its 1.0.40) and transformed the double callback to a "standard" err, res-callback.
This is not tested for all parts of the API but has been working flawlessly for message part of the API
I also converted some of the input arguments to conform to native JS when it comes to taking arguments for e.g. mergevars. This change is made for Messages.prototype.send and Messages.prototype.sendTemplate
Core Mandrill API way:
"global_merge_vars": [{
"name": "merge1",
"content": "merge1 content"
}],
"merge_vars": [{
"rcpt": "recipient.email#example.com",
"vars": [{
"name": "merge2",
"content": "merge2 content"
}]
}],
The expected way (and the way I changed it, naturally ;-)
"global_merge_vars": [{
"merge1": "merge1 content"
}],
"merge_vars": [{
"rcpt": "recipient.email#example.com",
"vars": [{
"merge2": "merge2 content"
}]
}],
If you like it, feel free to use it or clone it:
https://bitbucket.org/mraxus/mandrill-api-node/src
Cheers!

ASP.NET MVC model binding precedence vs. RESTful resources

The order of precedence that ASP.NET MVC uses when it binds models for incoming requests is bothering me in the context of REST. Essentially, MVC binds models using values in the following order of precedence:
POST body
Route (URL)
Query string values
What bothers me is how that trumps a resource's Uri with values from the body of the message.
For example, I could have a RESTful resource exposed as follows:
/dogs/
... returning:
[{
'name': 'Fido',
'color': 'brown',
'_links': {
'self': { 'href': '/dogs/7' }
}
},
{
'name': 'Spot',
'color': 'spotted',
'_links': {
'self': { 'href': '/dogs/5' }
}
}]
Note that with the "self" link (HAL style), I have everything I need to modify the dogs by PUTting those resources back to the server without needing their "id" values.
PUT /dogs/7
{
'name': 'Super Fido',
'color': 'rainbow'
}
The server has everything needed to update the dog, with no confusion. MVC will model-bind everything nicely into my model, including the id (sourced from the route).
However, some API styles I have seen include the 'id' in the message body, so that it looks like this:
GET /dogs/7
{
'id': 7,
'name': 'Super Fido',
'color': 'rainbow'
}
But fundamentally what bothers me the most is that if I have a route defined like "{controller}/{id}", and the client does the following:
PUT /dogs/7
{
'id': 5,
'name': 'Snowy',
'color': 'white'
}
... then MVC will model bind the 'id' to 5 (from the message body), and not 7 (from the route), yet based on the resource URI that my client provided, they should have been updating Fido's information. This would be akin to trying to save a document to your hard drive in a certain location, and because of something in the document, having it be automatically saved somewhere else.
How would one go about changing the out-of-the-box model binding precedence in ASP.NET MVC to prioritize the route values over the message body (when conflicts exist), and would this be a good thing to do in this context?

Rails 3 - Creating a JSON response to display Search Results

I'm working to have Rails 3 respond with a JSON request which will then let the app output the search results with the jQuery template plugin...
For the plugin to work, it needs this type of structure:
[
{ title: "The Red Violin", url: "/adadad/123/ads", desc: "blah yada" },
{ title: "Eyes Wide Shut", url: "/adadad/123/ads", desc: "blah yada" },
{ title: "The Inheritance", url: "/adadad/123/ads", desc: "blah yada" }
]
In my Rails 3 controller, I'm getting the search results which come back as #searchresults, which contain either 0 , 1 , or more objects from the class searched.
My question is how to convert that to the above structure (JSON)...
Thank you!
Update
Forgot to mention. The front-end search page will need to work for multiple models which have different db columns. That's why I'd like to learn how to convert that to the above to normalize the results, and send back to the user.
I am not really sure what is the problem here, since you can always call ".to_json" on every instance or collection of instances or hash, etc.
You can use .select to limit the number of fields you need, ie:
Object.select(:title, :url, :desc).to_json
I am guessing that the #searchresults is ActiveRecord::Relation, so you probably can use:
#searchresults.select(:title, :url, :desc).to_json

How do I get the Id of a button of a jquery UI dialog?

as the title says....
this is what I have tried but not working
$('#uxReferralAssessmentDetailsDialog').dialog({
autoOpen: false,
modal: true,
width: 400,
title: "Referral Assessment",
buttons: { "Save":{ id: 'uxbtnSaveAssessment', click:othis.OnAssessmentSave}, "Cancel": function() { $(this).dialog("close"); } }
});
I am using selenium and instead of the horrid xpath I want to use the id of each element to simplify the xpath
any ideas welcome
If you are having a hard time determining id as and other things that are being added to the html page by javascript on the fly. Try using a development tool for web browsers like firebug which is an addon for firefox:
See link for firebug addon for more information:
https://addons.mozilla.org/en-US/firefox/addon/1843

Resources