Reputation: 4047
This question is specifically because I'm using gon
, but conceptually it could apply to other cases, so I've tried to broaden it a bit. Gon is a nifty gem that allows you to declare a variable in your Rails controller and then use it in your Javascript. For example:
def index
gon.this = "that"
end
// index.html
<script>
console.log(gon.this)
// would print "that"
</script>
Specifically how this happens is that Gon injects a piece of script that declares a global variable, like so:
<script>
window.gon = {}
gon.this = "that"
</script>
The code that I'm using Jasmine to test looks like this:
// test.js
function loadProperPage() {
if (gon.this == "that") {
...
} else {
...
}
}
So as you can see, gon
is used immediately! My problem is that Jasmine keeps saying that gon
has not been defined, so I'm not sure how to "inject" it in a way that's semantically sensible. The only way that I can think of where it makes sense is to create a fake .js
file and require it as a source file in my javascript.yml
before I load the file I'm testing. I.e., it would look like this:
src_files:
- assets/gon_variables.js
- assets/test.js
But this is not a sustainable solution, because then I can't change the dummy variables in the gon_variables.js
file for different specs...
By that last sentence, what I mean is that I've been troubleshooting, and discovered that declaring gon
variables in either the fixture or the spec file itself will NOT work. I.e. both the below do NOT solve the problem
/////// spec file approach
//spec file
describe...
beforeEach(function() {
gon.this = "that"
})
})
/////// fixture file approach
// spec file
describe...
beforeEach(function() {
loadFixtures('test.html')
})
})
// test.html fixture
<head>
<script>
var gon = {permission: "new"}
</script>
</head>
<body>
...
</body>
Which brings me back to my question. My debugging apparently shows that the JS files in jasmine.yml
are loaded BEFORE either the fixtures or the spec file (and its before actions). Therefore, how else can you load dynamic code before the JS files in jasmine.yml
? Is there a helper that I can use or... ? Keep in mind the whole point of this is that I'd like to change the code I'm loading before the JS files depending on the spec. I.e., sometimes I want to have gon.this = "that"
but other times I'd like gon.this = "those"
Upvotes: 0
Views: 328