Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use rspec to mock a class method inside a module

Im trying to test a create method that has a call to an external API but I'm having trouble mocking the external API request. Heres my setup and what I've tried so far:

class Update
  def self.create(properties)
    update = Update.new(properties)

    begin
      my_file = StoreClient::File.get(properties["id"])
      update.filename = my_file.filename
    rescue
      update.filename = ""
    end    

    update.save  
  end
end


context "Store request fails" do
  it "sets a blank filename" do
    store_double = double("StoreClient::File")
    store_double.should_receive(:get).with(an_instance_of(Hash)).and_throw(:sad)
    update = Update.create({ "id" => "222" })
    update.filename.should eq ""        
  end
end

at the moment Im getting this failure

 Failure/Error: store_double.should_receive(:get).with(an_instance_of(Hash)).and_throw(:sad)
   (Double "StoreClient::File").get(#<RSpec::Mocks::ArgumentMatchers::InstanceOf:0x000001037a9208 @klass=Hash>)
       expected: 1 time
       received: 0 times

why is my double not working and how is best to mock the call to StoreClient::File.get, so that I can test the create method when it succeeds or fails?

like image 647
2 revs Avatar asked Feb 18 '23 07:02

2 revs


1 Answers

The problem is that double("StoreClient::File") creates a double called "StoreClient::File", it does not actually substitute itself for the real StoreClient::File object.

In your case I don't think you actually need a double. You can stub the get method on the StoreClient::File object directly as follows:

context "Store request fails" do
  it "sets a blank filename" do
    StoreClient::File.should_receive(:get).with(an_instance_of(Hash)).and_throw(:sad)
    update = Update.create({ "id" => "222" })
    update.filename.should eq ""        
  end
end
like image 165
Andrew Haines Avatar answered Mar 10 '23 06:03

Andrew Haines