Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalidate Sprockets cache during RSpec automated test

In my Rails application, I have a .js.erb file that has a variable which gets dynamically set based on some Ruby code.

var myTimer = <%= MyApp.config.timeout_time * 1000 %>;

The app works fine, but I'm having a problem in some automated tests. The problem occurs in an RSpec feature test that works with this JavaScript. My spec file has a number of tests that change the ruby MyApp.config.timeout_time time on the fly to test out different scenarios. In my spec file, the first example passes, and the rest fail.

I finally realized this is happening because myTimer never gets updated on the JavaScript side. When the first test runs, the JavaScript gets compiled using the current value as it's set in Ruby. When I change the Ruby timer for the second test, RSpec is still using the previous value in the JavaScript.

Is there a way to tell Sprockets/Rails to invalidate a file or a part of the cache so the JavaScript will get rebuilt? I don't want to turn off caching in general, I just need a way to invalidate application.js on a per-test basis when needed.

I may be able to "touch" one of the JavaScript files on the file system to make sprockets think the file has been changed, but I don't really want to do that.

like image 485
CodeSmith Avatar asked Nov 09 '22 11:11

CodeSmith


1 Answers

I don't know how to do what you asked. But you could consider setting myTimer to the value you want it to be in the feature specs that need it to be a specific value.

Assuming you're using Capybara, you can run Javascript in a feature spec with

page.execute_script('// some Javascript')

You might need to rearrange your Javascript a bit first to put myTimer somewhere where a script can change it.

like image 150
Dave Schweisguth Avatar answered Nov 15 '22 06:11

Dave Schweisguth