方法存根于 before(:all) [英] 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
当我使用 before(:each)
代替 before(:all)
时,它可以工作.但是如果使用 before(:all)
它会抛出错误为 undefined method proxy_for for nil:NilClass
.我找不到原因.请你帮助我好吗?提前致谢.
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.
推荐答案
聚会迟到?是的,但不介意从我发现的东西中扣除我自己的一分钱.我在尝试在 RSpec.configure
块中存根请求时遇到了类似的错误,以便存根仅可用于我通过 config.around(:each, option)
选项.
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.
所以,这意味着我在单个示例范围之外使用了 RSpec::Mocks
不支持的存根 这里!.解决方法是在上下文中使用临时作用域.
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.
所以你有
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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!