Hi,

I was hoping to reduce some repetitive verbosity in our specs,
and came across an attractive pattern.

First, in a helper file:

    def when_subscribed(&block)
      context "when user gets subscribed experience" do
before { current_user.stub(subscribed?: true) }
class_eval(&block)
      end
    end

    def when_unsubscribed(&block)
      context "when user gets subscribed experience" do
before { current_user.stub(subscribed?: false) }
class_eval(&block)
      end
    end

Then in our specs, stuff like:

    when_subscribed do
      it "allows the user to access some page" do
        ...
      end

      ...
    end

This works of course, except it no longer lets us run these specs
via a line number on the command line, because RSpec considers
the spec defined in our helper file.

In other words, the example group metadata says the file_path and
line_number correspond to the "context" lines in the
when_[un]subscribed definition.

The only solution I could find was a horrible brittle hack like:

    def shadow_context(name, options={}, &block)
      first_caller_from_outside_rspec = caller.find { |line| line !~ 
%r'/lib/rspec/core|/spec/support/' }
      first_caller_from_outside_rspec =~ /(.+?):(\d+)(|:\d+)/
      file_path, line_number = $1, $2.to_i
      context name do
metadata[:example_group][:file_path] = file_path
metadata[:example_group][:line_number] = line_number
class_eval(&block)
      end
    end

And now change "context" to "shadow_context" in the helpers.

Is there a better way to do this?
If not, would a better way to handle this be welcome in RSpec?

Thanks!
George

-- 
You received this message because you are subscribed to the Google Groups 
"rspec" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msg/rspec/-/hfyzcrp4E4gJ.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to