在Rspec中模拟TCPSocket [英] Mock TCPSocket in Rspec
问题描述
我有一个简单的方法,可以连接到TCP服务器,并放入单行字符串并关闭连接.关闭连接后,该方法将重定向到特定页面.
I have a simple method which connects to a TCP server and puts single line of string and closes the connection. After the connection is closed the method redirects to a particular page.
我有兴趣测试该方法的重定向,并且不关心TCP连接值.因此,我最好的解决方法是模拟连接.这是方法,
I am in interested in testing the redirection of that method and do not care about the TCP connection values. Thus, my best option to get around is to mock the connection. Here is the method,
def print
server = TCPSocket.new('a.b.c.d', 56423)
server.puts "Hello Everyone"
server.close
redirect_to root_url
end
我的测试看起来像
it 'redirects to root_url' do
get :print
expect(response).to redirect_to(root_url))
end
我的问题是,我不知道如何模拟连接,以便可以转到重定向部分.有什么想法吗?
My problem is, I do not know how to mock the connection so that I can get to the redirect part. Any thoughts?
推荐答案
There are many ways to do this, as described in https://www.relishapp.com/rspec/rspec-mocks/v/3-0/docs. They vary in terms of syntax and the extent to which they constrain the execution.
最宽松的方法之一是在get
调用之前添加以下内容:
One of the most permissive approaches would be to include the following prior to your get
call:
server = double('server').as_null_object
TCPSocket.stub(:new).and_return(server)
这将允许/忽略传递给TCPSocket.new
的任何参数,并忽略传递给该调用返回的对象的所有消息/参数.
This would permit/ignore any arguments passed to TCPSocket.new
and ignore all messages/arguments passed to object returned from that call.
这篇关于在Rspec中模拟TCPSocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!