Verifying Context

19 views
Skip to first unread message

Panayotis Matsinopoulos

unread,
Sep 2, 2016, 8:25:46 AM9/2/16
to rspec
Hi,

I would like to have your opinion on the following.

I have found very useful to verify the context of an example. What do I mean? See the following example:

describe MyClass do
  describe '#process' do
    context 'when something is a Hash' do
       let(:something) { build(:something) }

       before do
          expect(something).to be_a(Hash)
       end

       it 'returns an open struct' do
         expect(subject.process(something)).to be_a(OpenStruct)
       end
    end
  end
end

Do you see that in the before block I am verifying that the context of the "it" is correct?

To me, this has been proven very useful. Because sometimes, the context setup code might not be doing what we are expecting it to do. The verification code does the double check.

What is your opinion about this practice? Is this a practice that you apply too? Or am I overprotective?

Panos

Myron Marston

unread,
Sep 2, 2016, 8:49:42 AM9/2/16
to rspec
In general, yes, I've also found it useful to express pre-conditions as expectations in some situations.  I usually do this when I've realized that the test I'm writing has a non-obvious assumption that, if it was ever violated due to a config change or some other change, would cause the test to pass without exercising the code I intend it to.  You don't want a future change to cause a test to start passing only because it's no longer exercising the logic it is intended to cover.

That said, in the example you gave, it's not clear to me what the value is.  Are you concerned that `build` might one day change to no longer return a Hash?

HTH,
Myron

Panayotis Matsinopoulos

unread,
Sep 5, 2016, 6:09:35 AM9/5/16
to rspec
Thank you Myron for the answer. It's very clear.

I built the above example just to explain my question/case. Let's not worry about the particulars of this example. 

It is the idea of validating the context and your answer covers it very well. I am also on the same page like you are.

However, there are some people that they find strange using "expect(...)" to validate the test context. In order to make it clear, they like the idea to check the validity
of the test context. What they don't like is the usage of the "expect(...)" method to do that.

Is there any other RSpec suggested method to do that? For example, when using Jasmine, I use the "fail(...)" method which I call if
the test context is not valid (in the before block again). If not, I was thinking about creating a helper method like "validate_context(...)" that would
raise an error like "RSpec::ContextValidityError", and that I could call for such cases in which I want to validate the context.

What are your thoughts?

Panos
Reply all
Reply to author
Forward
0 new messages