ruby – 如何使用rspec模拟模块内的类方法
发布时间:2020-12-17 03:39:10 所属栏目:百科 来源:网络整理
导读:我试图测试一个调用外部API的create方法,但我在模拟外部API请求时遇到问题.继承了我的设置以及到目前为止我尝试过的内容: class Update def self.create(properties) update = Update.new(properties) begin my_file = StoreClient::File.get(properties["i
我试图测试一个调用外部API的create方法,但我在模拟外部API请求时遇到问题.继承了我的设置以及到目前为止我尝试过的内容:
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的调用,以便我可以在成功或失败时测试创建方法? 解决方法
问题是double(“StoreClient :: File”)创建了一个名为“StoreClient :: File”的double,它实际上并不代替真正的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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 我可以为联合的C函数设置默认参数
- ruby – SAVON是否支持客户端证书身份验证
- Postgresql 自增语句
- the server didn't send back a proper XML response.
- ruby-on-rails – Rails:.destroy错误的参数数量(0表示1)
- c# – NHibernate:在集合上调用.RemoveAll
- 用Ajax+js+jQuery实现无闪烁定时刷新页面 定时刷新
- Reactor模式详解
- ajax请求里面调用window.open会被浏览器拦截(优化版)
- c – 应该是std :: vector :: swap()与有状态的分配器无效所