How to test a sprockets custom directive?

Env: Rails 6, Sprockets version: 3.7.2 (discourse uses this version of sprockets)

Hi guys, I’m a newbie here. Recently, I wrote a custom sprockets directive namely require_tree_discourse for a discourse plugin. I’m looking for a way to write unit tests for it.

I added a new method to the DirectiveProcessor class.

What I’m looking for is a way to say this. i.e.

// file_with_requires.js
//= require_tree_discourse discourse/app/lib

Read the file with my custom directive and return the list of files it resolves to and compare it with the actual list of files found in that folder.

Sorry, if I’m not clear enough.

Your question piqued my curiosity. It does not look like Sprockets does unit tests for directives like require_tree.

It looks like Sprockets tests in an integration-y way by compiling an asset that contains the directive and then asserting on the output. Here’s an example: sprockets/test_asset.rb at 2c38d99930421c22896a65e1d384edf90830f4c3 · rails/sprockets · GitHub

You could write an integration test in the same style as Sprockets to test it.

3 Likes

Thanks for the pointers. @bensheldon I’ll read up the code and try to write something similar in my context.

1 Like

@bensheldon Yuhoo. I was able to write specs for it. In my context, the directive was needed for loading a tree outside of the load path hence I had to add both the load path along the path where the file(with directives) was located. Here’s the code(not sure it would make sense in the general rails context though).

1 Like

Thanks @bensheldon We’re finally using the new directive in production. I’ve also described our use case on the official discourse forum.