How to use rspec to bully a class method inside a module

I am trying to test the create method that has an external API call, but I am having trouble mocking the external API request. Here is my setup and what I have 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 

Im currently receiving this denial

  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 what is the best way to make fun of calling StoreClient::File.get so that I can test the create method when it StoreClient::File.get or fails?

+4
source share
1 answer

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

In your case, I do not think you really need a double. You can StoreClient::File get method in the StoreClient::File object 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 
+8
source

All Articles