【问题标题】:How to stub method in initialize with rspec如何使用 rspec 初始化存根方法
【发布时间】:2015-06-02 18:59:09
【问题描述】:
class Party
    attr_accessor :number
  include Validations

    def initialize
        self.number = proccess_args(2)
        puts luhn?
    end

    def proccess_args(opt)
        ARGV[opt].downcase
    end
end

需要'spec_helper'

describe Party do
  before :each do

    new_method = Party.method(:new)
    allow(self).to receive(proccess_args).with(2).and_return('add')
    @party = Party.new 
  end
end

spec_helper.rb require_relative '../'

require 'yaml'

如何使用 rspec 来确保 proccess_args 未被实际调用,而是被模拟以避免 ARGV 破坏我的测试?例如,我想伪造 proccess_args(2) 的调用以返回“Jason Wade”,并避免 ARGV[opt] 被 rspec 触及。

【问题讨论】:

  • 向您展示规格文件会很有帮助
  • 我已经包含了测试

标签: ruby-on-rails ruby rspec rspec-rails


【解决方案1】:

allow(ARGV).to receive(:downcase).and_return('whatever')

你告诉 RSpec 到 allow ARGVreceive 一个名为 :downcase and_return 'whatever' 的方法,而不是在被测试的代码中实际调用它。 (这部分可能不是特别有用,但正是这种解释让我在脑海中点击。)

【讨论】:

  • 你可以试试,它似乎不起作用,并且在 proccess_args 中失败:(
  • 编辑原始帖子以添加测试文件的代码。我发布的那行只是存根本身,而不是测试。
  • 完成,我只是想构建那个对象来编写测试。
  • 我正在使用 ruby​​ 2.1.3p242 和 rspec (3.2.0)
  • 这仍然失败,我不知道为什么。
猜你喜欢
  • 1970-01-01
  • 2017-09-19
  • 1970-01-01
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多