t6d t6d - 1 year ago 61
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)

# ... 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



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 Source

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 }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download