Domanda

I'm trying to update an instance variable @status on an object based on the performance of a block. This block also makes calls to another class.

def run
  @entries.keep_if { |i| valid_entry?(i) }.each do |e|
    begin
      unique_id = get_uniqueid e
      cdr_record = Cdr.find_by_uniqueid(unique_id).first
      recording = cdr_record.nil? ? NullAsteriskRecording.new : AsteriskRecording.new(cdr_record, e)
      recording.set_attributes
      recording.import
    rescue Exception => e
      fail_status
    end
  end
end

fail_status is a private method that updates the instance variable to :failed. Through breaking some other things, I've basically verified this code works, but I want a test in place as well. Currently, I've got the following:

context "in which an exception is thrown" do
  before do
    @recording = double("asterisk_recording")
    @recording.stub(:import).and_raise("error")
  end

  it "should set #status to :failed" do
    # pending "Update instance variable in rescue block(s) of #run"
    subject.run
    subject.status.should eq :failed
  end
end

But the test always fails. The rescue block is never evaluated (I checked with a puts statement that would be evaluated when I hardcoded in a raise statement). Am I using the double feature wrong, here? Or am I doing myself in by stubbing out an exception, so the rescue block never gets run?

È stato utile?

Soluzione

You set up @recording in your before block, but the code you have posted for your run method will not use that @recording instance and therefore the call to recording.import in the run method will not raise an exception.

In your run method, recording can either end up being an instance of NullAsteriskRecording or AsteriskRecording. If you know that it is going to be an AsteriskRecording as your current test implies, one approach would be to change your before block to the following:

before do
  AsteriskRecording.any_instance.stub(:import).and_raise("error")
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top