5
votes

I'm trying to create a double but I keep getting this error:

 undefined method `double' for #<Class:0x007fa48c234320> (NoMethodError)

I suspect the problem has got to do with my spec helper so I'm adding my spec helper below:

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))

require 'rspec'
require 'webmock/rspec'
include WebMock::API
include WebMock::Matchers

Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }

RSpec.configure do |config|
end
2
where / how are you calling double ?Frederick Cheung
within my describe block before the it block.tommi
double exists inside examples (and before() blocks etc) but it sounds like you're trying to call it outside one of those contexts.Frederick Cheung
@FrederickCheung it works now. thanks! i shall go read up to reenforce some understanding.tommi
@FrederickCheung: perhaps you could make an answer from your commment so this question is not left unanswered.zetetic

2 Answers

14
votes

double exists inside examples (and before blocks etc) but it sounds like you're trying to call it outside one of those contexts.

So for example

describe Thing do
  thing = double()
  it 'should go bong'
  end
end

is incorrect but

describe Thing do
  before(:each) do
    @thing = double()
  end

  it 'should go bong' do
    other_thing = double()
  end
end

is fine

9
votes

You can also use RSpec's double outside of RSpec by requiring the standalone file.

require "rspec/mocks/standalone"

greeter = double("greeter")
allow(greeter).to receive(:say_hi) { "Hello!" }
puts greeter.say_hi

From the docs: https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/outside-rspec/standalone