6

I have a question which is really specific. I don't want to do a controller test but a requests test. And I don't want to use Capybara because I don't want to test user interaction but only response statuses.

I have the following test under spec/requests/api/garage_spec.rb

require 'spec_helper'

describe "Garages" do

  describe "index" do
    it "should return status 200" do
      get 'http://api.localhost.dev/garages'
      response.status.should be(200)
      response.body.should_not be_empty
    end
  end
end

This works. But as I have to do more tests.. is there any way to avoid to repeat this? http://api.localhost.dev

I tried with setup { host! 'api.localhost.dev' } But it doesn't do anything. A before(:each) block setting @request.host to something, of course crashes because @request is nil before performing any http request.

The routes are set correctly (and in fact they work) in this way

namespace :api, path: '/', constraints: { subdomain: 'api' } do
  resources :garages, only: :index
end

2 Answers 2

6

You can create a helper method in the spec_helper.rb, something like:

def my_get path, *args
  get "http://api.localhost.dev/#{path}", *args
end

And its usage will be:

require 'spec_helper'

describe "Garages" do

  describe "index" do
    it "should return status 200" do
      my_get 'garages'
      response.status.should be(200)
      response.body.should_not be_empty
    end
  end
end
1
  • Interesting idea. But in this way every action should have its own helper. I could end writing more code than the the one I want to dry! Commented Jul 9, 2014 at 11:15
4

Try this:

spec_helper.rb

RSpec.configure do |config|
  config.before(:each, type: :api) do |example|
    host! 'api.example.com'
  end
end

your spec file

require 'spec_helper'

describe "Garages", type: :api do

  describe "index" do
    it "should return status 200" do
      get 'garages'
      response.status.should be(200)
      response.body.should_not be_empty
    end
  end
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.