Dynamic subject in example groups

33 views
Skip to first unread message

Steve V

unread,
Dec 4, 2017, 11:34:33 AM12/4/17
to rspec
how can I dynamically set the subject for a spec? I have a bunch of describe blocks that set the subject like this `subject { Types::Event.fields['latitude'] }`, where `Types::Event` is the `described_class`. The name of the describe block in this case is 'latitude'.

Is there a way to get that name from the group, and set it on the subject, or maybe do something using a metadata flag?

Thanks,
Steve

Myron Marston

unread,
Dec 4, 2017, 3:01:00 PM12/4/17
to rs...@googlegroups.com

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.

Reply all
Reply to author
Forward
0 new messages