In a subject block, you can access the example (and it’s metadata) by adding a block argument. So if you wanted to define a subject based on the described_class and the group description, you could do:
subject { |ex| described_class.fields[ex.metadata[:example_group][:description]] }
To take this a step further, you could define this in a shared context to make it easy to apply this to multiple example groups:
RSpec.shared_context "dynamic field subject" do
subject { |ex| described_class.fields[ex.metadata[:example_group][:description]] }
end
Then you can include this by using include_context:
RSpec.describe Types::Event do
describe "latitude" do
include_context "dynamic field subject"
# ...
end
end
Taking this a step further, if you wanted to auto-include the shared context, you can do so using config:
RSpec.configure do |config|
config.include_context "dynamic field subject", :needs_dynamic_field_subject
end
Any group tagged with :needs_dynamic_field_subject will automatically have this context included. You could even use define_derived_metadata to automatically tag the desired groups with : needs_dynamic_field_subject:
RSpec.configure do |config|
config.define_derived_metadata do |meta|
meta[:needs_dynamic_field_subject] if satisfies_your_criteria?(meta)
end
end
(The definition of satisfies_your_criteria? is left as an exercise to the reader).
All that said: once you’ve done all that, things are wired up in a pretty implicit manner, which can become quite confusing. The power is there in RSpec to do this, but it doesn’t necessarily mean you should. Think carefully about the tradeoffs involved and if it is the right solution for your project.
My book Effective Testing with RSpec 3 has a lot more detail about this stuff if you want to know more.
HTH,
Myron
--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+unsubscribe@googlegroups.com.
To post to this group, send email to rs...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/1a3c2601-4e41-4ab6-8085-2cf3ae2e9676%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.