Last Updated: September 09, 2019
·
3.435K
· avgp

Share RSpec examples that make multiple requests

Say you have a bunch of controllers and all of them need to behave in a specific way (for example they should all respond with a BAD_REQUEST when parameters are missing) and you want to check it for a whole set of parameters like this:

it "should check for missing parameters" do
  params = { :required1 => "a", :required2 => "b" }
  params.each_key do |key|
    result = request_proc.call(params.except(key))
    result.should be_bad_request
  end
end

Now, assuming that you implemented this in ApplicationController, you cannot be sure, that each controller really behaves like this (it may be overridden).
You could repeat this snippet in every controller, but that is not DRY.

The third option is to create a sharedexamplesfor group and pass a proc for making the request, to keep it portable between the different requests:

shared_examples_for "ApplicationController" do |params|
  it "should complain about missing parameters" do
    params.each_key do |key|
      result = request_proc.call(params.except(key))
      result.should be_bad_request
    end
  end
end

and use it in your specs:
describe "POST 'new'" do
let(:requestproc) { lambda { |params| post 'new',params } }
it
behaves_like "ApplicationController", { :required1 => "a", :required2 => "b"}