Rspec从数组生成“它做”

时间:2013-05-28 15:24:43

标签: rspec rspec2 rspec-rails

如何从数组生成测试

describe "some test" do
  let(:some) { generated_array }

  # raise error - undefined local variable or method
  some.each do |key|
    it "#{key} test" do
      true
    end
  end

  # will work
  [1,2,3].each do |key|
   ...

end

如何用RSpec重新分析?

1 个答案:

答案 0 :(得分:1)

由于RSpec是DSL,您无法在外部上下文中使用let进行测试。在运行测试之前,RSpec首先读取示例spec文件。在执行任何实际测试之前,它会在DSL解析期间点击some.each

此错误是因为some在示例对象上定义,但describecontext在示例组对象上下文中运行。

你可以看到:

describe 'thing' do
  p self.ancestors
  #=> [#<Class:0x007fa97a0761f8>, RSpec::Core::ExampleGroup, RSpec::Matchers,
  #    RSpec::Core::MockFrameworkAdapter, RSpec::Core::SharedExampleGroup,
  #    RSpec::Core::Pending, RSpec::Core::Extensions::InstanceEvalWithArgs,
  #    RSpec::Core::ExampleGroup::LetDefinitions,
  #    RSpec::Core::ExampleGroup::NamedSubjectPreventSuper,
  #    RSpec::Core::MemoizedHelpers, Object, PP::ObjectMixin, Kernel,
  #    BasicObject]

  it { p selfs }
  #=> #<RSpec::Core::ExampleGroup::Nested_1:0x007f8d1b397790 ...>
end