When using RSpec to test deeply nested data structures, I find the need to define subjects in nested contexts in terms of the subjects in the containing contexts. I have looked extensively but not found any examples on how to do with without defining many variables. It complicates the specs and limits the possibility of spec reuse. I am curious whether there is a way to do this in RSpec as it stands and, if not, what would be a good way to approach the problem.
Right now, my code looks something like:
context 'with a result which is a Hash' do
before do
@result = get_result()
end
subject { @result }
it { should be_a Hash }
context 'with an Array' do
before do
@array_elem = @result[special_key]
end
subject { @array_elem }
it { should be_an Array }
context 'that contains a Hash' do
before do
@nested_hash = ...
end
subject { @nested_hash }
...
end
end
end
Instead, I'd rather write something along the lines of:
context 'with a result which is a Hash' do
subject { get_result }
it { should be_a Hash }
context 'with an Array' do
subject { parent_subject[special_key] }
it { should be_an Array }
context 'that contains a Hash' do
subject { do_something_with(parent_subject) }
...
end
end
end
What's a way to extend RSpec with this type of automatic subject hierarchy management?