【发布时间】:2021-07-05 04:25:06
【问题描述】:
所有单元测试用例都应该被模拟/存根。用于检查错误方法和结果方法的 Rspec。
require 'yaml'
require_relative 'checkerror'
class Operations
def initialize
@path
@checks_to_run
@check
end
# This will prints the result of each file offences or no offences
def result (result_log: File.new('result.txt', 'a+'))
# @check.errors should be stubbed with a value to enter in if or else block
if @check.errors.empty?
# Output is printing in both console as well as file
result_log.write("#{@check.checker.file_path} :: No offensenses detected\n")
puts "#{@check.checker.file_path} :: No offensenses detected\n"
else
@check.errors.uniq.each do |err|
puts "#{@check.checker.file_path} : #{err}\n"
result_log.write("#{@check.checker.file_path} : #{err}\n")
end
end
result_log.close
end
def rules_to_run
@checks_to_run = YAML.load(File.read('lib/property.yaml'))
end
def path_of_directory
@path = gets.chomp
end
def checkerror
Dir[File.join(@path, '**/*.rb')].each do |file|
@check = CheckError.new(file)
@check.check_alphabetized_constants if @checks_to_run.include?('check_alphabetized_constants')
@check.check_empty_line_before_return if @checks_to_run.include?('check_empty_line_before_return')
#result is called to print errors
result
end
end
end
我已经为 checkerror 方法编写了 rspec
context '#checkerror' do
it 'only check the method is called or not' do
allow(@check_to_run).to receive(:include?).and_return(true)
allow(@check).to receive(:check_alphabetized_contants)
operation = Operation.new
operation.checkerror
expect(@check).to have_received(:check_alphabetized_constants)
end
end
但出现错误
TypeError: no implicit conversion of nil into string.
我认为还没有进入 do-end 块的循环,并且我猜存根在语法上也是错误的。
【问题讨论】:
-
请编辑您的问题以添加完整的堆栈跟踪和任何允许重现您的错误的 rspec 初始化程序。
-
这是一个非常令人沮丧的问题,因为当底层代码实际上没有意义时,您正在为 rspec 实现寻求非常具体的帮助。正如我之前提到的那样,您实际上并未将
@path或@check_to_run变量设置为任何内容,因此此代码实际上无效;你希望Dir[File.join(nil, '**/*.rb')].each ....做什么?! -
换句话说,你不能这样做:
operation = Operation.new。您的Operation类至少期望使用path和checks_to_run进行初始化。我将尝试在答案中为您重写此内容,但您确实需要退后一步并编写一个有效的实现,然后再进行单元测试。 -
当然。我会做的