如何使用Rspec更改请求测试中的子域(用于API测试)

jon*_*net 6 ruby rspec ruby-on-rails

我有一个非常具体的问题.我不想做一个控制器测试,而是一个请求测试.而且我不想使用Capybara因为我不想测试用户交互但只想测试响应状态.

我在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
Run Code Online (Sandbox Code Playgroud)

这有效.但是因为我必须做更多的测试..有没有办法避免重复这个?http://api.localhost.dev

我尝试过setup { host! 'api.localhost.dev' }但它没有做任何事情.阿before(:each)块设置@request.host的东西,当然崩溃,因为@request是在执行任何HTTP请求之前为零.

通过这种方式正确设置路径(实际上它们可以正常工作)

namespace :api, path: '/', constraints: { subdomain: 'api' } do
  resources :garages, only: :index
end
Run Code Online (Sandbox Code Playgroud)

Uri*_*ssi 5

您可以在其中创建一个辅助方法spec_helper.rb,例如:

def my_get path, *args
  get "http://api.localhost.dev/#{path}", *args
end
Run Code Online (Sandbox Code Playgroud)

它的用法是:

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
Run Code Online (Sandbox Code Playgroud)