t6d t6d - 4 months ago 8
Ruby Question

Is it possible to access the subject of the surrounding context in Rspec?

The following code doesn't work, but it best show what I'm trying to achieve

context "this context describes the class" do

subject do
# described class is actually a module here
c = Class.new.extend(described_class)
c.some_method_that_has_been_added_through_extension
c
end

# ... testing the class itself here ...

context "instances of this class" do

subject do
# this doesn't work because it introduces a endless recursion bug
# which makes perfectly sense
subject.new
end

end

end


I also tried to use a local variable in the inner context that I initialized
with the subject, but no luck. Is there any way I can access the subject of a outer scope from within my subject definition in the inner scope?

t6d t6d
Answer

Something that obviously works is using an instance variable in the inner context and initializing it not with the subject but subject.call instead. Subjects are Procs. Hence, my first approach didn't work.

context "instances of this class" do

  klass = subject.call
  subject { klass.new }

end