【发布时间】: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发布示例。我建议仅在您真正需要它们时使用Let和Let!。
标签: unit-testing rspec