我正在为我的 API 实现 rswag。在运行任何示例(GET、POST)之前,需要完成一部分设置。这就是基本设置。但是,对于每个请求(GET、POST 等),在初始设置之后可能需要进行额外的设置,因为它会继续处理这些记录。
我习惯于编写集成测试(类型::功能),在后台我会设置对之后所有场景都有效的数据库,如果需要,每个场景都可以在数据库中添加更多记录。
下面是一个简化的例子。before(:all)部分在创建 @speech的部分之后运行,这会导致由于 @device 不存在而无法创建语音。
require 'swagger_helper'
RSpec.describe 'api/speech', type: :request do
before(:all) do
@organisation = create(:organisation, :with_departments, organisation_type: 'care_home')
@device = @organisation.devices.first
end
path '/api/v1/speech/{uuid}' do
get 'Get speech details' do
security [ Bearer: { scopes: ['speech'] } ]
parameter name: :uuid, in: :path, type: :string
response "200", "Get details of a speech event" do
authenticate_oauth([:speech])
@speech = Speech::SpokenAnnouncement.create(message: Faker::Lorem.sentence(word_count: 5), destinations: [@device.id])
let(:uuid) { @speech.uuid }
run_test!
end
end
end
path '/api/v1/speech' do
post 'Speak a sentence' do
security [ Bearer: { scopes: ['speech'] } ]
parameter name: :speech, in: :body, schema: {
type: :object,
properties: {
message: { type: :string },
destinations: { type: :array, items: { type: :integer, nullable: false } }
}
}
response "200", "Successfully added speech event" do
authenticate_oauth([:speech])
let(:speech) { {'message': 'This is a spoken message.', 'destinations' => [@device.id] } }
run_test! do |response|
expect(Speech::SpokenAnnouncement.count).to eq(1)
end
end
end
end
end
所以我的问题是:如何在每个请求(GET、POST 等)之前运行设置部分,以便我可以为每个请求定义更多设置。
希望这很清楚。