方法存根之前(:全部)

Siv*_*lli 11 rspec rspec-rails

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
Run Code Online (Sandbox Code Playgroud)

当我使用它before(:each)而不是before(:all)它的作用.但如果使用before(:all)它会抛出错误undefined method proxy_for for nil:NilClass.我找不出原因.请你帮助我好吗?提前致谢.

El'*_*ico 11

迟到了?是的,但是我不介意从我发现的东西中减去一分钱.我在尝试在RSpec.configure块中存根请求时遇到了类似的错误,因此存根仅对我传递config.around(:each, option)选项的示例可用.

所以,这意味着我在个别示例的范围之外使用存根,RSpec::Mocks 这里不支持!解决方法是在上下文中使用临时范围.

所以你有了

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
Run Code Online (Sandbox Code Playgroud)

HTH!


Pet*_*vin 8

before(:all)不推荐使用,但before(:all)不支持使用来自rspec-mocks的双精度数.有关背景,请参阅github问题中的引用问题.

当前master版本的rspec-mocks将与3.0.0.beta2一起使用,将失败,并显示以下错误:

The use of doubles or partial doubles from rspec-mocks outside of the per-test lifecycle is not supported.
Run Code Online (Sandbox Code Playgroud)

先前版本将undefined method proxy_for ...在存根点生成错误.


hlc*_*lcs 5

这应该工作:

require "rspec/mocks/standalone"
before(:all) do
Run Code Online (Sandbox Code Playgroud)