Mock TCPSocket in Rspec

你说的曾经没有我的故事 提交于 2020-01-16 06:09:26

问题


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.

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

My test looks something like,

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?


回答1:


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.

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)

This would permit/ignore any arguments passed to TCPSocket.new and ignore all messages/arguments passed to object returned from that call.



来源:https://stackoverflow.com/questions/20847554/mock-tcpsocket-in-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!