Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method stubbing on before(:all)

require './spec/spec_helper'
require './bank'

describe Bank do
  context "#transfer" do
    before(:all) do
      @customer1 = Customer.new(500)
      customer2 = Customer.new(0)
      @customer1.stub(:my_money).and_return(1000)
      customer2.stub(:my_money).and_return(0)
      @transfer_message = Bank.new.transfer(@customer1, customer2, 2000)
    end 

    it "should return insufficient balance if transferred amount is greater than balance" do
      expect(@transfer_message).to eq("Insufficient funds")
    end 

    it "calls my_money" do
      expect(@customer1).to have_received(:my_money)
    end 
  end 
end

When I use before(:each) instead before(:all) it works. But if use before(:all) it throws error as undefined method proxy_for for nil:NilClass. I couldn't find out the reason. Could you please help me? Thanks in advance.

like image 334
Siva Gollapalli Avatar asked Jan 20 '14 13:01

Siva Gollapalli


People also ask

What is stubbing in RSpec?

In RSpec, a stub is often called a Method Stub, it's a special type of method that “stands in” for an existing method, or for a method that doesn't even exist yet. Here is the code from the section on RSpec Doubles − class ClassRoom def initialize(students) @students = students End def list_student_names @students.

What is stub instance?

Use any_instance.stub on a class to tell any instance of that class to. return a value (or values) in response to a given message. If no instance. receives the message, nothing happens.

How do I mock an instance variable in RSpec?

You can't mock an instance variable. You can only mock methods. One option is to define a method inside OneClass that wraps the another_member , and mock that method. However, you don't have to, there is a better way to write and test your code.

What is mocking in Ruby?

Mocking is a technique in test-driven development (TDD) that involves using fake dependent objects or methods in order to write a test.


1 Answers

Late to the party? Yeah, but wouldn't mind to drop my own one cent from what I discovered. I encountered a similar error while trying to stub a request in a RSpec.configure block so that the stub will only be available to examples I pass the config.around(:each, option) option to.

So, that means I was using the stub outside the scope of individual examples which is not supported by RSpec::Mocks here!. A work around is to use a temporary scope in the context.

So you have

before(:all) do
  RSpec::Mocks.with_temporary_scope do
    @customer1 = Customer.new(500)
    customer2 = Customer.new(0)
    @customer1.stub(:my_money).and_return(1000)
    customer2.stub(:my_money).and_return(0)
    @transfer_message = Bank.new.transfer(@customer1, customer2, 2000)
  end
end

HTH!

like image 117
El'Magnifico Avatar answered Oct 16 '22 05:10

El'Magnifico