Reputation: 999
I maintain a gem that gathers data from various APIs. For APIs that require an API key, I have implemented scrapers to fall back on when no API key is set.
My current solution to testing both the scraper and the API code is to have two spec files that are virtually the same except for a before hook.
In the API spec, I have a before(:each)
hook that explicitly sets the API key.
In the scraper spec, I have a before(:each)
hook that explicitly nullifies the API key.
Aside from those two different hooks, the specs are essentially the same. However, there are one or two instances where the API spec differs from the scraper spec, so I'd need the ability to handle that. I imagine just checking to see whether or not the API key is set will be enough for this.
Another thing to note is that I don't want to rerun my entire test suite, as only a very small fraction of the codebase has both an API and scraper. I basically need to be able to set it on a per-spec basis.
Thanks in advance for any help that you guys can provide!
EDIT: Think I have a solution. Will provide details when I get a full implementation.
Upvotes: 1
Views: 634
Reputation: 21810
This is what RSpec's shared examples are for. Use like so:
RSpec.shared_examples_for "an API component" do
let(:api_client) { APIClient.new }
it "foos" do
expect(api_client).to foo
end
it "bars" do
expect(api_client).to bar
end
end
RSpec.describe API do
it_behaves_like "an API component" do
before(:each) { set_api_key }
end
end
RSpec.describe Scraper do
it_behaves_like "an API component" do
before(:each) { nullify_api_key }
end
end
Upvotes: 3