我有以下类:我想确保类url仅为所有实例设置一次.
class DataFactory
@@url = nil
def initialize()
begin
if @@url.nil?
Rails.logger.debug "Setting url"
@@url = MY_CONFIG["my value"]
end
rescue Exception
raise DataFactoryError, "Error!"
end
end
end
Run Code Online (Sandbox Code Playgroud)
我有两个测试:
it "should log a message" do
APP_CONFIG = {"my value" => "test"}
Rails.stub(:logger).and_return(logger_mock)
logger_mock.should_receive(:debug).with "Setting url"
t = DataFactory.new
t = nil
end
it "should throw an exception" do
APP_CONFIG = nil
expect {
DataFactory.new
}.to raise_error(DataFactoryError, /Error!/)
end
Run Code Online (Sandbox Code Playgroud)
问题是第二个测试从不抛出异常,因为@@ url类变量仍然是在第二个测试运行时从第一个测试设置的.即使我在第一次测试结束时将实例设置为nil,但在第二次测试运行之前,垃圾收集还没有清除内存:
任何想法都会很棒!我听说你可能会使用Class.new,但我不知道该怎么做.
嗨,我并尝试rspec模拟以下类:
class Person
def initialize(personid)
Rails.logger.debug "Creating person with id #{personid}"
end
end
Run Code Online (Sandbox Code Playgroud)
使用这个:
require 'spec_helper'
describe Person do
describe "#initialize" do
let(:rails_mock) { double("Rails").as_null_object }
let(:logger_mock) { double("Rails.logger").as_null_object }
it "logs a message" do
rails_mock.stub(:logger).and_return(logger_mock)
logger_mock.should_receive(:debug)
Person.new "dummy"
end
end
end
Run Code Online (Sandbox Code Playgroud)
并得到此消息:
RSpec :: Mocks :: MockExpectationError:(双倍“ Rails.logger”)。debug(任何参数)
预期:1次
收到:0次
任何帮助将是巨大的!