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.
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.
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.
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.
Mocking is a technique in test-driven development (TDD) that involves using fake dependent objects or methods in order to write a test.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With