【问题标题】:RSpec: Using a each loop for similar it blocksRSpec:对类似的 it 块使用 each 循环
【发布时间】:2021-08-04 12:43:47
【问题描述】:

我正在编写测试来检查某些端点是否返回 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

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

【问题讨论】:

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


    【解决方案1】:

    您可以使用shared example

    
    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
    

    【讨论】:

    • 这是 100% 的路要走。在我看来,共享示例是 RSpec 中一个未被充分利用的组件(尤其是对于 API 测试)。在之前的一个项目中,我设法将 47 个不同模型的 CRUD 逻辑测试浓缩为一组共享示例(带有嵌套共享示例),消除了数千行测试代码,尤其是在不同上下文中复制和粘贴。如果多个文件中的测试存在标准模式,则共享示例是迄今为止保持测试干净和一致的最佳方式
    【解决方案2】:

    John's answer 很好,尤其是在每个端点有更多规范的情况下。

    至于您的尝试,这是范围界定的一个简单错误。您的实例变量设置在一个级别,但在另一个级别上使用。将其设置在同一级别。

      describe 'Status of below end points should be 200 -->' do
        end_points = ['one', 'two', 'three', 'four', 'five']
        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
    

    【讨论】:

      猜你喜欢
      • 2014-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      相关资源
      最近更新 更多