use*_*651 5 ruby rspec mocking rspec2
我有一个包含两个类的文件。
class LogStash::Filters::MyFilter< LogStash::Filters::Base
Run Code Online (Sandbox Code Playgroud)
和
class LogStash::JavaMysqlConnection
Run Code Online (Sandbox Code Playgroud)
JavaMysqlConnection有方法initialize和select。它由MyFilter类使用,用于查询数据库,您可能已经猜到了。
我如何模拟initialize和select方法分别返回 nil 和一个数组?
我尝试使用:
before(:each) do
dbl = double("LogStash::JavaMysqlConnection", :initialize => nil)
end
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为我仍然看到通信链接失败。
我有 rspec 版本 2.14.8
提前致谢。附注。我是 Ruby 新手
坏(工作):
allow_any_instance_of(LogStash::JavaMysqlConnection)
.to receive(:select)
.and_return([])
Run Code Online (Sandbox Code Playgroud)
好的:
let(:logstash_conn) { instance_double(LogStash::JavaMysqlConnection) }
allow(LogStash::JavaMysqlConnection)
.to receive(:new)
.and_return(logstash_conn)
allow(logstash_conn)
.to receive(:select)
.and_return([])
Run Code Online (Sandbox Code Playgroud)
根据安德烈的回应,对我有用的解决方案是:
before(:each) do
mock_sql = double(:select=> sql_select_return)
allow(LogStash::JavaMysqlConnection).to receive(:new).and_return(mock_sql)
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8743 次 |
| 最近记录: |