chrishough chrishough - 6 months ago 48
Ruby Question

rails 4 rspec let support method error

I have been working to use the proper rspec syntax for setting variables for example

let(:order_created) { load_json_fixture('order_created') }
which calls this support method inside
rspec/support
:

Support Method

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


However, wherever I try to call this I get the following error message:

Error

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 >


Partial Spec Example

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


I can get around this by using instance variables but I am trying to follow rspec correctly. Thoughts on how to fix this?

Answer

Try it this way:

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