Hack your Rspec setup using tagsI ran into an issue in rspec the other day where I had a
beforeblock to setup about 10 different tests, but I needed to write one more that was similar enough that it belonged in the same
contextbut it required slightly different setup so the
beforeblock I already defined.
What to do? I could break out the existing tests into a nested
contextblock and use the setup there, then do another nexted
contextblock for my new test, but I really didn’t want to do that because all these tests should belong in the same context. I just wanted to skip the
beforeblock on one specific test.
Rspec tags to the rescue!
In this case, my new test was a JS test and all others were not (which is partly why the setup was different. So, the test was already tagged
js: true, and in mybefore` block, I modified it like so:
before(:each) do |test|
# Run this only on tests NOT tagged with js: true
if test.example.metadata[:js] == nil
# Existing setup code
Works like a charm, and I still have all my related tests within the same context like I wanted.
Hat Tip: http://stackoverflow.com/questions/27864080/how-can-i-skip-some-setup-for-specific-rspec-tags