如何用rswag单独测试指定API路径或文件?
单独测试RSwag指定API路径的方法
我有一个使用rswag生成OpenAPI文档的Ruby项目,接口路径按分类存储在不同Ruby文件中。新增API端点生成Swagger文档时,不想运行所有文件和路径验证文档正确性,希望单独测试指定路径(比如示例中的「Creates a blog」)或文件。示例代码如下:
# spec/requests/blogs_spec.rb require 'swagger_helper' describe 'Blogs API' do path '/blogs' do post 'Creates a blog' do tags 'Blogs' consumes 'application/json' parameter name: :blog, in: :body, schema: { type: :object, properties: { title: { type: :string }, content: { type: :string } }, required: [ 'title', 'content' ] } response '201', 'blog created' do let(:blog) { { title: 'foo', content: 'bar' } } run_test! do # some logics end end response '422', 'invalid request' do let(:blog) { { title: 'foo' } } run_test! do # some logics end end end end path '/blogs/{id}' do get 'Retrieves a blog' do tags 'Blogs', 'Another Tag' produces 'application/json', 'application/xml' parameter name: :id, in: :path, type: :string request_body_example value: { some_field: 'Foo' }, name: 'basic', summary: 'Request example description' response '200', 'blog found' do schema type: :object, properties: { id: { type: :integer }, title: { type: :string }, content: { type: :string } }, required: [ 'id', 'title', 'content' ] let(:id) { Blog.create(title: 'foo', content: 'bar').id } run_test! do # some logics end end response '404', 'blog not found' do let(:id) { 'invalid' } run_test! do # some logics end end response '406', 'unsupported accept header' do let(:'Accept') { 'application/foo' } run_test! do # some logics end end end end end
我需要仅测试「Creates a blog」路径,该如何在spec文件中添加标签?同时,当前在docker-compose中使用bundle exec rake rswag:specs:swaggerize执行命令,也需要知道如何修改。
1. 给指定API路径添加RSpec标签
在要单独测试的请求块(比如post 'Creates a blog')中,添加RSpec自定义标签,有两种方式:
方式一:在请求块内添加元数据
post 'Creates a blog' do tags 'Blogs' # 添加自定义RSpec标签 metadata tag: :create_blog # 原有代码保持不变... end
方式二:在请求声明时直接传入标签
# 把标签直接作为参数传入post方法 post 'Creates a blog', tag: :create_blog do tags 'Blogs' # 原有代码保持不变... end
标签名可以自定义,只要后续命令中使用的标签名和这里一致即可。
2. 单独运行带指定标签的测试
本地命令
使用ADDITIONAL_RSPEC_OPTS参数指定要运行的标签,命令如下:
bundle exec rake rswag:specs:swaggerize ADDITIONAL_RSPEC_OPTS="--tag create_blog"
如果只想运行某个特定文件(比如blogs_spec.rb),可以直接指定文件路径:
bundle exec rake rswag:specs:swaggerize ADDITIONAL_RSPEC_OPTS="spec/requests/blogs_spec.rb"
也可以同时指定文件和标签,精准定位:
bundle exec rake rswag:specs:swaggerize ADDITIONAL_RSPEC_OPTS="spec/requests/blogs_spec.rb --tag create_blog"
Docker Compose中的命令修改
在docker-compose.yml的command字段中,直接添加ADDITIONAL_RSPEC_OPTS参数:
# 仅运行带create_blog标签的测试 command: bundle exec rake rswag:specs:swaggerize ADDITIONAL_RSPEC_OPTS="--tag create_blog"
如果需要同时指定文件和标签:
command: bundle exec rake rswag:specs:swaggerize ADDITIONAL_RSPEC_OPTS="spec/requests/blogs_spec.rb --tag create_blog"
内容的提问来源于stack exchange,提问作者nipuna
相关产品推荐
相关产品推荐

