Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec.config before(:each) except for specific :types

I am trying to get a before(:each) block to run for all specs except type: :feature.

The only way I can get it working is to cut-and-paste and have separate config blocks for each type. (:type => :model, :type => :service, etc.)

spec/rails_helper.rb

# To speed up tests, stub all Paperclip saving and reading to/from S3
config.before(:each, :type => :model) do
  allow_any_instance_of(Paperclip::Attachment).to receive(:save).and_return(true)
end

Is there a more DRY approach?

like image 852
madcow Avatar asked Sep 18 '15 15:09

madcow


2 Answers

What you're passing into your before block, is a 'conditions hash'. RSpec will only apply the before to those examples or contexts that match those conditions.

The hash is fairly flexible and you can do straight forward things such as type: :model as you've done, but you can query any type of metadata, with arbitrary names.

As an example from filter run excluding

  :foo => 'bar'
  :foo => /^ba/
  :foo => lambda {|v| v == 'bar'}
  :foo => lambda {|v,m| m[:foo] == 'bar'}

:foo could be anything for example, type. But it gives you a load of flexibility, especially with the lambda syntax to be able to very specific under what circumstances you want to run your specs.

In your case you could do something like this:

config.before(:each, :type => lambda {|v| v != :feature}) do
  allow_any_instance_of(Paperclip::Attachment).to receive(:save).and_return(true)
end
like image 106
Yule Avatar answered Oct 11 '22 05:10

Yule


You could use unless to judge example metadata via an around hook.

RSpec.configure do |config|
  config.around(:each) do |example|
    example.run unless example.metadata[:type].eql? :feature
  end
end
like image 25
Johnson Avatar answered Oct 11 '22 05:10

Johnson