看this blog post,我正在尝试设置我使用匹配器Object.should have_received(:action).with(*params)
的能力,但似乎无法得到它。为了解决问题,我写了一个非常简单的rake任务:
# lib/tasks/check_log.rake
namespace :check_log do
# other tasks omitted
desc "Task description"
task :test => :environment do
ImportRecording.log.debug "Something"
end
end
这是我在spec/lib/tasks/check_log_rake_spec.rb
require_relative '../../support/shared_contexts/rake'
# other requirements omitted
describe "check_log:test", focus: true do
include_context "rake"
let(:log_name) { "import.log" }
let(:checker) { CheckLog.new log_name }
let(:import_log) { ImportRecording.log }
let(:message) { "Asterisk import finished!" }
it "verify a method was called on a log" do
subject.invoke
ImportRecording.log.should have_received(:debug).with("Something")
end
end
由上述博客文章提供,这是我的共享背景,在spec/support/shared_contexts/rake.rb
require "rake"
shared_context "rake" do
let(:rake) { Rake::Application.new }
let(:task_name) { self.class.top_level_description }
let(:task_path) { "lib/tasks/#{task_name.split(":").first}" }
subject { rake[task_name] }
def loaded_files_excluding_current_rake_file
$".reject {|file| file == Rails.root.join("#{task_path}.rake").to_s }
end
before do
Rake.application = rake
Rake.application.rake_require(task_path,[Rails.root.to_s],loaded_files_excluding_current_rake_file)
Rake::Task.define_task(:environment)
end
end
所以我安装了rspec-spies
gem并将以下行添加到我的spec_helper
require `rspec-spies`
但是当我运行测试时,我收到以下错误:
Failure/Error: ImportRecording.log.should have_received(:debug).with("Something")
expected #<Logger:0x007ffbbe4638b0 @progname=nil, @level=0, @default_formatter=#<Logger::Formatter:0x007ffbbe463108 @datetime_format=nil>,
@formatter=#<Logger::SimpleFormatter:0x007ffbbe462960 @datetime_format="%F %T">,
@logdev=#<Logger::LogDevice:0x007ffbbe462f28 @shift_size=1048576, @shift_age=0,
@filename="/Users/brad/code/ruby/rails_projects/rl4/log/import.log",
@dev=#<File:/Users/brad/code/ruby/rails_projects/rl4/log/import.log>,
@mutex=#<Logger::LogDevice::LogDeviceMutex:0x007ffbbe462e60 @mon_owner=nil,
@mon_count=0, @mon_mutex=#<Mutex:0x007ffbbe462af0>>>,
@mock_proxy=#<RSpec::Mocks::Proxy:0x007ffbbae76a68 @object=#<Logger:0x007ffbbe4638b0 ...>,
@name=nil, @error_generator=#<RSpec::Mocks::ErrorGenerator:0x007ffbbae76a18 @declared_as="Mock",
@target=#<Logger:0x007ffbbe4638b0 ...>, @name=nil>,
@expectation_ordering=#<RSpec::Mocks::OrderGroup:0x007ffbbae769c8 @ordering=[]>,
@messages_received=[], @options={}, @already_proxied_respond_to=false,
@null_object=false>> to have received :debug with ["Something"]
但是,我已经确认该线正在写入。我是否错误地使用了这种方法,或者有人能指出正确的方向吗?
答案 0 :(得分:2)
根据this README,我误解了测试间谍。它们实际上是一个两步过程,你必须在其中
have_received
匹配器来验证实际调用的存根是什么对我的测试进行这些更改已解决了我的所有问题。