I have the following class: I want to ensure the class url is only set once for all instances.
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
I have two tests:
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
The problem is the second test never throws an exception as the @@url class variable is still set from the first test when the second test runs. Even though I have se the instance to nil at the end of the first test garbage collection has not cleared the memory before the second test runs:
Any ideas would be great! I did hear you could possibly use Class.new but I am not sure how to go about this.
One can stop the RSpec test in the middle by pressing ctrl-C twice.
Ruby has four types of variable scope, local, global, instance and class. In addition, Ruby has one constant type. Each variable type is declared by using a special character at the start of the variable name as outlined in the following table. In addition, Ruby has two pseudo-variables which cannot be assigned values.
Class variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.
describe DataFactory before(:each) { DataFactory.class_variable_set :@@url, nil } ... end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With