我有一个gem,它有一个根据Rails.env的不同行为的方法:defself.envifdefined?(Rails)Rails.envelsif...现在我想编写一个规范来测试这个代码路径。目前我是这样做的:Kernel.const_set(:Rails,nil)Rails.should_receive(:env).and_return('production')...没关系,只是感觉很丑。另一种方法是在spec_helper中声明:moduleRails;end而且效果也很好。但也许有更好的方法?理想情况下,这应该有效:rails=double('Rails')rails.sho
我正在使用rspec-mock进行测试驱动开发。我开始实现单个类并使用rspec-mock模拟/stub其他类。尚未实现的类的模拟对象效果很好。但是,当我尝试模拟一个尚不存在的类的类方法时,我没有成功。我的类“哈希”应该有一个类方法“calculate_hashes”接收文件名并返回哈希。我试过了allow(Hashes).toreceive(:calculate_hash)do|file|#looksupwhattoreturnend给出错误“Hashesisnotaclass”。然后我实现了一个类“Hashes”classHashesend然后只尝试以相同的方式对类方法进行stub
我的Ruby-on-Rails项目中有以下文件结构,用于规范:/spec/msd/serviceservice_spec.rb/support/my_modulerequests_stubs.rb我的request_stubs.rb有:moduleMyModule::RequestsStubsmodule_functiondeflist_clientsurl="dummysite.com/clients"stub_request(:get,url).to_return(status:200,body:"clientsbody")endend在我的service_spec.rb我有:re
我正在尝试测试命令行工具的输出。如何使用rspec来“伪造”命令行调用?执行以下操作不起作用:it"shouldcallthecommandlineandreturn'text'"do@p=Pig.new@p.should_receive(:run).with('my_command_line_tool_call').and_return('resulttext')end如何创建stub? 最佳答案 使用newmessageexpectationsyntax:规范/虚拟规范.rbrequire"dummy"describeDummy
我有一个对象MyObject:classMyObjectdefinitialize(options={})@stat_to_load=options[:stat_to_load]||'test'enddefresults[]endend仅当stat_to_load="times"时,我才想stubresults方法。我怎样才能做到这一点?我试过了:MyObject.any_instance.stubs(:initialize).with({:stat_to_load=>"times"}).stubs(:results).returns(["klala"])但它不起作用。有什么想法吗?
我正在构建Rails应用程序并使用RSpec制定测试。我为我正在创建的名为current_link_to的方法编写了测试。此方法应该检查当前页面是否对应于我传递给它的路径,并将current类添加到生成的链接中,以防它匹配。这是规范:require"spec_helper"describeApplicationHelperdodescribe"#current_link_to"dolet(:name){"Products"}let(:path){products_path}let(:rendered){current_link_to(name,path)}context"whenthe
我有一个看起来像这样的类:classFoo在测试#nasty_bars_present?我想编写一个rspec测试来对bars关联进行stub,但允许where自然执行。像这样的东西:describe"#nasty_bars_present?"docontext"withnastybars"dobefore{foo.stub(:bars).and_return([mock(Bar,bar_type:"Nasty")])}it"shouldreturntrue"doexpect(foo.nasty_bars_present?).tobe_trueendendend上面的测试给出了一个关于
我正在对用户的提要进行分页,并想模拟我正在使用的API的响应。API可以返回奇怪的结果,所以我想确保如果API返回我已经看到的项目,请停止分页。我使用minitest在第一次调用方法get_next_page时stub,但我想在第二次和第三次用不同的值调用它时stub。我应该只使用rSpec吗?ruby新手...这是片段test"crawlerdoesnotpaginateifnonewitemsinnextpage"do#1:A,B#2:B,D=>D#3:A=>stopcrawler=CrawlJob.newfirst_page=[{"id"=>"item-A"},{"id"=>"i
有什么方法可以使用Minitest::Mock验证从未调用过或仅调用过多次的方法提前致谢 最佳答案 具体次数:Minitest::Mock强制开发人员明确消息预期,因此如果您希望给定方法被调用x次,您需要非常直白。my_mock=Minitest::Mock.newx.times{my_mock.expect:some_method,:return_val}从未调用过:从哲学上讲,Minitest避免测试没有发生的事情。虽然不完全相似,但请查看thispost或谷歌“minitestassertnothingraised”。Mini
Variants这个问题已被多次问到,但大多数都与摩卡有关,而我没有使用它。我是Rails的新手,所以这看起来微不足道,但我无法在我的规范文件中使用mock(用于名为competitions的Controller)。require'rails_helper'require'spec_helper'describeCompetitionsControllerdobefore:eachdo@fake_c=mock(Competition,:competition_id=>1,:competition_name=>'one',:competition_des=>'any')enddescri