获取"`let`不能从一个例子中获得"在Rails 4和Rspec中

时间:2016-06-03 20:08:43

标签: ruby-on-rails ruby rspec

我一直在努力使用正确的Rspec语法设置变量,例如在let(:order_created) { load_json_fixture('order_created') }内调用此支持方法的rspec/support

支持方式

module LoadJsonFixtureHelper
  def load_json_fixture(name)
    data = nil
    Dir["#{Rails.root}/{test,spec}"].each do |dir|
      Dir["#{dir}/fixtures/**/*.json"].map do |filename|
        data = JSON.parse(File.read(filename)) if File.basename(filename,File.extname(filename)) == name
      end
    end
    data
  end
end

但是,无论我在哪里尝试调用此方法,都会收到以下错误消息:

错误

test - (#<RSpec::ExampleGroups::Provider::FromAFactory:0x007fe8d2213c58>):0 > let(:order_created) { load_json_fixture('order_created') }
RSpec::Core::ExampleGroup::WrongScopeError: `let` is not available from within an example (e.g. an `it` block) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). It is only available on an example group (e.g. a `describe` or `context` block).
from /Users/chrishough/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-3.4.4/lib/rspec/core/example_group.rb:683:in `method_missing'
test - (#<RSpec::ExampleGroups::Provider::FromAFactory:0x007fe8d2213c58>):0 >

部分规范示例

RSpec.describe Provider, type: :model do
  describe 'from a factory' do

    before(:all) do
      binding.pry
    end


    it 'can be built' do

      binding.pry

      expect((build :provider)).to be_valid.and be_instance_of(Provider)
    end

    it 'can be created' do
      expect((create :provider)).to be_valid.and be_persisted
    end
  end

我可以通过使用实例变量解决这个问题,但我正在尝试正确地遵循Rspec。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

以这种方式尝试:

describe 'from a factory' do
  let(:order_created) { load_json_fixture('order_created') }

  it 'can parse json' do
    # try typing 'order_created` now when pry trigger  
    binding.pry

  end
end