gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:05:37 25 4
gpt4 key购买 nike

我有一个非常具体的问题。我不想进行 Controller 测试,而是进行请求测试。而且我不想使用 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

这行得通。但是因为我必须做更多的测试..有什么办法可以避免重复这个吗? http://api.localhost.dev

我尝试使用 setup { host! 'api.localhost.dev' } 但它什么也没做。before(:each) block 将 @request.host 设置为某物,当然会崩溃,因为 @request 在执行任何 http 请求之前为 nil。

路由以这种方式正确设置(事实上它们有效)

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

最佳答案

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

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

它的用法是:

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

关于ruby-on-rails - 如何使用 Rspec 更改请求测试中的子域(用于 API 测试),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24652085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com