【问题标题】:Rspec. The tested code is automatically started after test规格。测试后代码自动启动
【发布时间】:2016-10-26 07:25:58
【问题描述】:

我在测试 Sensu 插件时遇到问题。 每次我启动 rspec 测试插件时都会对其进行测试,但无论如何在测试结束时,原始插件都会自动启动。所以我在我的控制台中有:

Finished in 0 seconds (files took 0.1513 seconds to load) 
1 example, 0 failures 
CheckDisk OK:       # This comes from the plugin

简要说明我的系统如何工作: 插件调用系统'wmic'命令,处理它,检查磁盘参数的条件并返回退出状态(ok,critical等) Rspec 模拟来自系统的响应并设置到插件的输入中。最后,当给出模拟输入时,rspec 检查插件退出状态。

我的插件是这样的:

require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-plugin/check/cli'

class CheckDisk < Sensu::Plugin::Check::CLI
  def initialize
    super
    @crit_fs = []
  end

  def get_wmic
    `wmic volume where DriveType=3 list brief`
  end

  def read_wmic
    get_wmic
    # do something, fill the class variables with system response  
  end

  def run
   severity = "ok"
   msg = ""
   read_wmic
   unless @crit_fs.empty?
     severity = "critical"  
  end  
  case severity
    when /ok/
      ok msg
    when /warning/
      warning msg
    when /critical/
      critical msg
    end
  end
end

这是我在 Rspec 中的测试:

require_relative '../check-disk.rb'
require 'rspec'

  def loadFile
    #Load template of system output when ask 'wmic volume(...)
  end

  def fillParametersInTemplate (template, parameters)
    #set mocked disk parameters in template
  end

  def initializeMocks (options)
    mockedSysOutput = fillParametersInTemplate @loadedTemplate, options 
    po = String.new(mockedSysOutput)
    allow(checker).to receive(:get_wmic).and_return(po) #mock system call here
  end

  describe CheckDisk do
    let(:checker) { described_class.new }
    before(:each) do   
       @loadedTemplate = loadFile   
       def checker.critical(*_args)
          exit 2
       end    
     end

  context "When % of free disk space = 10 >" do 
    options = {:diskName => 'C:\\', :diskSize => 1000, :diskFreeSpace => 100}       
    it 'Returns ok exit status ' do      
      begin                   
        initializeMocks options
        checker.run 
      rescue SystemExit => e 
        exit_code = e.status   
      end 
      expect(exit_code).to eq 0
    end  
  end 
end

我知道我可以在最后一个示例之后加上“exit 0”,但这不是解决方案,因为当我尝试启动许多规范文件时,它会在第一个之后退出。如何只开始测试,而不运行插件?也许有人可以帮助我并展示如何处理这样的问题? 谢谢。

【问题讨论】:

    标签: ruby rspec mocking sensu


    【解决方案1】:

    您可以存根原始插件调用并可选择返回一个虚拟对象:

    allow(SomeObject).to receive(:method) # .and_return(double)
    

    您可以将它放在before 块中,以确保所有断言都将共享代码。

    另一件事是您使用rescue 块来捕获代码因错误中止时的情况。您应该改用raise_error 匹配器:

    expect { run }.to raise_error(SystemExit)
    

    【讨论】:

    • 感谢您的回复。但是插件代码在最后一步之后仍然执行...... BTW:如何使用raise_error匹配器检查退出代码(插件返回0,1还是2)?
    • 这意味着你没有模拟正确的方法。您还可以允许代码执行并模拟标准输出 (allow(STDOUT).to receive(:write))。这取决于你想要真正测试什么。至于SystemExit,则无法查看退出码。
    猜你喜欢
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多