2012-12-04 80 views
4

我试图测试一个调用外部API的创建方法,但我无法模拟外部API请求。继承人我的设置和我到目前为止已经试过:如何使用rspec来模拟模块内的类方法

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 

目前即时得到这个故障

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 

为什么我的双重不工作,以及如何最好通话嘲笑到StoreClient::File.get,这样我可以在成功或失败时测试创建方法吗?

回答

8

的问题是,double("StoreClient::File")创建一个双称为“StoreClient ::文件”,实际上它并不代替自己的真实StoreClient::File对象。

在你的情况下,我不认为你实际上需要一个双。您可以直接存根StoreClient::File对象上get方法如下:

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 
+0

我收到一个错误说'私有方法被调用为UxFactory :: AppDirectory:Class'当我尝试这一点。任何想法可能会导致它? 'should_receive'调用起作用,但是当代码(在我测试过的类中)试图调用失败的方法时:( –

+0

)如何使用新的'expect'语法编写这个测试用例? – aks

相关问题