How to change subdomain in query test using Rspec (for testing API)

I have a question that is really specific. I do not want to perform a quiz, but a query test. And I do not want to use Capybara, because I do not want to test user interaction, but only the response statuses.

I have the following test on 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 

It works. But since I have to do more tests, is there a way to avoid repeating this? http://api.localhost.dev

I tried with setup { host! 'api.localhost.dev' } setup { host! 'api.localhost.dev' } But it does nothing. A before(:each) blocks @request.host setting for something, of course, a failure, because @request is zero before any HTTP request is made.

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

 namespace :api, path: '/', constraints: { subdomain: 'api' } do resources :garages, only: :index end 
+6
source share
2 answers

You can create a helper method in spec_helper.rb , for example:

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

And its use 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 
+5
source

Try the following:

spec_helper.rb

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

your specification 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 
+2
source

Source: https://habr.com/ru/post/971969/


All Articles