Understanding Turbolinks by Reading Tests
The Turbolinks Readme documents the library’s workings in great details. To fully get it, we might build a rails 5 app and try it out. But there’s a faster way to get to know the library and its working - by reading the test cases in the source.
This section explains how we can first run the whole test suite after cloning the repo locally.
Once cloned and setup, the
bin/blade runner command runs all test cases (the
QUnit library is used as the test library).
The automated tests are hard to make sense of without trying them manually. For example, this testcase - “following a same-origin unannotated link” asserts that clicking a TL enabled link,
- triggers a
- after which the url of the current page is asserted to be the new url
- and that, the action that was used to do the
Turbolinks.visitwas ‘push’, that is, the
history.pushState()api (and not the
replaceStateor full page load)
Wouldn’t it be nice to see it ourselves?
All you have to do is 2 things:
- copy the
turbolinks.jsfile from ‘dist/’ dir to ‘test/src/` dir
- cd into the
test/srcdir and serve up all the files using a http server serving command. I use the
servecommand, which is just this alias:
alias serve='echo '\''ruby -run -e httpd . -p 3000'\'' && ruby -run -e httpd . -p 3000'
And then, followup with the coffee testcases and visit the corresponding files in the fixtures folder.
Things I learnt from going through the test cases:
- annotating a link with
data-turbolinks-action=replacewill make it go to a different page, but in the process overwrite the current page’s entry in the index. So you can’t go back to the page you came from
data-turbolinks=falsewill make Turbolinks leave the anchor alone. It will just make it do full page load. This the world knows. But an enclosed link within this disabled element will also ignore TL, unless you add a
data-turbolinks=trueto the inner anchor
target=\_blanklinks always ignore TL and do a full page load
- we know that when a TL enabled link is clicked, the
turbolinks:loadevent will be triggered. But before that,
turbolinks:after-renderis fired. (There are many other events too.)
- all asset elements - link, script etc - are tracked by TL if
data-turbolinks-track=reloadis present. It means that when the assets change in the server, TL will know to do a full page reload instead of just relying on the cached version. That’s why the random numbers appended to the application.js and application.css files in rails are very important.
metaelements are ‘accumulated’ in the root page of the app. For every TL visit we do that has these meta tags, those elems are gathered and put into root page’s head element.
- To programmatically visit a different page in the app, we’ll usually do
window.location=/bar.html. But that makes the browser to do a full page reload not using TL. To programmatically trigger a turbolink enabled url, use