首页 > 解决方案 > RSpec:对类似的 it 块使用 each 循环

问题描述

我正在编写测试以检查某些端点是否返回 200 状态。

RSpec.describe 'API -> ' do
  before do
    @token = get_token
  end

  describe 'Status of below end points should be 200 -->' do

    it "/one should return a status code of 200" do
      get("/api/v1/one", params: {
        authentication_token: @token
      })
      expect(response.status).to eql(200)
    end

    it "/two should return a status code of 200" do
      get("/api/v1/two", params: {
        authentication_token: @token
      })
      expect(response.status).to eql(200)
    end

    it "/three should return a status code of 200" do
      get("/api/v1/three", params: {
        authentication_token: @token
      })
      expect(response.status).to eql(200)
    end

  end
end

有很多这样的端点,我想知道是否有更有效的方法来写这个,比如

RSpec.describe 'API -> ' do
  before do
    @token = get_token
    @end_points = ['one', 'two', 'three', 'four', 'five']
  end

  describe 'Status of below end points should be 200 -->' do
    @end_points.each do |end_point|
      it "/#{end_point} shold returns a status code of 200" do
        get("/api/v1/#{end_point}", params: {
          authentication_token: @token
        })
        expect(response.status).to eql(200)
      end
    end
  end
end

但这不起作用并给出错误each called for nil

对此的任何帮助都会很棒,谢谢。

标签: rubyruby-on-rails-5rspec-rails

解决方案


您可以使用的是共享示例


shared_examples "returns 200 OK" do |endpoint|
 let(:token) { get_token }

 it "should return a status code of 200" do
   get(endpoint, params: { authentication_token: token })
   expect(response.status).to eql(200)
 end
end

describe '..' do
  include_examples 'returns 200 OK', '/api/endpoint/1'
  include_examples 'returns 200 OK', '/api/endpoint/2'
end

推荐阅读