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.
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!
before(:all)
is not deprecated, but use of doubles from rspec-mocks in before(:all)
is not supported. See the referenced issues in github issue for background.
The current master
version of rspec-mocks, to be available with 3.0.0.beta2, will fail with the following error:
The use of doubles or partial doubles from rspec-mocks outside of the per-test lifecycle is not supported.
Prior versions will generate the undefined method proxy_for ...
error at the point of stubbing.
This should work:
require "rspec/mocks/standalone"
before(:all) do
来源:https://stackoverflow.com/questions/21235269/method-stubbing-on-beforeall