【问题标题】:rspec build many tests at once with each, problem with memoized variablesrspec 一次构建许多测试,记忆变量的问题
【发布时间】:2020-07-02 14:48:37
【问题描述】:

我需要构建一些非常重复的 rspec 测试,并且想稍微干一下。

describe 'filter' do
  let!(:filter_1) { create :filterable, value: 1 }
  let!(:filter_2) { create :filterable, value: 2 }
  let!(:filter_3) { create :filterable, value: 3 }
  let!(:filter_4) { create :filterable, value: 4 }

  expected = { 
              a: filter_1,
              b: filter_2,
              c: filter_3,
              d: filter_4
            }
  expected.each do |filter, expected| 
    describe "by #{filter}" do
      let(:expected) { [ expected ] }
      it "shows only #{filter}" do
        get :index, filter: filter
        expect(assigns[:filters]).to match_array expected
      end
    end
  end
end

我基本上是用我的过滤器和预期结果定义一个哈希,并为每一个构建一个测试。

问题是如何在哈希中指定预期的结果。

此示例引发错误:

rspec-core-3.4.4/lib/rspec/core/example_group.rb:667:in `method_missing': `filter_1` 
is not available on an example group (e.g. a `describe` or `context` block). 
It is only available from within individual examples (e.g. `it` blocks) 
or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). 
(RSpec::Core::ExampleGroup::WrongScopeError)```

I think the memoized variables are only available within an `it` block. 

how could I solve this? 

thanks, 

【问题讨论】:

  • 您应该尝试使用方法或Proc 的解决方案我将使用Proc 发布示例。我建议仅在您真正需要它们时使用LetLet!

标签: unit-testing rspec


【解决方案1】:
describe 'filter' do
  expected_filters = -> () do
    filter_1 =  '1'
    filter_2 = '2'
    { a: filter_1, b: filter_2 }
  end
  
  

  expected_filters.().each do |filter, expected| 
    describe "by #{filter}" do
      it "shows only #{filter}" do
        expect(filter).to be_instance_of(Symbol)
        expect(expected).to be_instance_of(String)
      end
    end
  end
end

但是,如果您需要为任何示例运行 Let! 中的代码,请尝试找到具有方法定义的解决方案,但您必须按实际情况更改测试代码中的某些内容。

【讨论】:

    猜你喜欢
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多