Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top