One can write tests for the backend of a plugin. For example, I created the following file in my plugin directory:
spec/lib/route_store_spec.rb
:
require 'rails_helper'
describe MyPlugin::RouteStore do
describe ".get_routes" do
it "should return a Hash" do
expect(described_class.get_routes().is_a?(Hash)).to be true
end
end
end
And then, I run the tests like this from Discourse’s root directory:
bundle exec rake plugin:spec["my-plugin-dir"]
/!\ Update: Should you get the error zsh: no matches found: plugin:spec[my-plugin-dir]
, that’s a known issue with zsh. You can workaround it by running the tests like this instead:
bundle exec rake "plugin:spec[my-plugin-dir]"
Old content before adding the update note
First of all, the following for running the tests don’t work although I see it recommended as the way to run the tests in the forum a lot:
-
bundle exec rake plugin:spec["disraptor"]
: Errors withzsh: no matches found: plugin:spec[disraptor]
-
bundle exec rake plugin:spec disraptor
: errors on a different plugin’s tests with:Failure/Error: class DetectedLink < Struct.new(:url, :is_quote); end TypeError: superclass mismatch for class DetectedLink
Now, I have a general question regarding testability of certain code. The method I want to test in the code above looks like this:
described_class.get_routes()
:
def get_routes
return PluginStore.get(MyPlugin::PLUGIN_NAME, 'key') || {}
end
Both parameters of PluginStore.get
are hard-coded and currently cannot be changed from within the tests. This makes the method untestable because I would need to test actual plugin data from the store which I cannot rely on being there.
Discourse’s own tests for the discourse-narrative-bot
plugin work around this by making the key parameter a parameter in the method they want to test (see plugins/discourse-narrative-bot/spec/discourse_narrative_bot/store_spec.rb
for reference).
Are there other options for testing a plugin’s store?