Specify shared_context used with conditions in example group
Created by: avit
This is not a fully realized example, but some kind of functionality similar to this could help make it easier to use shared contexts.
Currently, calling include_context
within an example group, and global RSpec.configuration.include_context
have a subtle but major difference that is not documented:
- In global configuration, the context is not included globally, but metadata filters get registered instead.
- Under the example group, the metadata filters argument is ignored, and the shared context is included directly.
It's not exactly clear that this happens from reading the docs, and there is no warning where the filters are ignored. (There is also no example in the docs that shows how a shared_context
can be declared locally within a group.)
Ultimately, I would like a way to more easily scope shared contexts with metadata filters, and combine them with shared examples to write a test matrix. Maybe this fictional example will show what I'm after:
RSpec.describe "polling" do
# DECLARE EXPECTED OUTCOMES AS SHARED EXAMPLES
shared_examples "vote counted" do
# ...
end
shared_examples "vote discarded" do
# ...
end
shared_examples "voter turned away" do
# ...
end
# DECLARE DIMENSIONS IN THE TEST MATRIX AS SHARED CONTEXTS
shared_context "is registered" do
let(:voter_status) { :registered }
end
shared_context "is unregistered" do
let(:voter_status) { nil }
end
shared_context "is early" do
let(:poll_open) { true }
end
shared_context "is late" do
let(:poll_open) { false }
end
# REGISTER CONTEXTS FOR METADATA CONDITIONS
# (This is the part where I'm dreaming)
include_context "is registered", registered: true
include_context "is unregistered", unregistered: true
include_context "is early", early: true
include_context "is late", late: true
# TEST MATRIX
context "as a good citizen", :registered, :early do
it_behaves_like "vote counted"
end
end
The obvious workaround is to manually include_context
repeatedly where each one applies. It just seems like there could be a way to use filters to make things more readable & easier to spot that all the permutations are covered.