0

Background: I am unit testing a game server which is built upon rails 4.1.1 and separate socket.io/node.js for socket messaging. Messages from node.js to rails are going through RESTful http requests. Single test case runs as follows:

(1) rake unit test --> (2) rails controller --> (3) node.js/socket.io --> (4) rails controller

Problem description: Some DB entries are created with ActiveRecord at step (2), then upon receiving a socket message at step (3) node.js sends HTTP request back to rails controller and finally(!!) at step (4) rails controller tries to access DB entries from step (2), but TEST DB contents are empty at this point.

Question: It seems like desired behavior of rake to cleanup TEST DB, but how can I persist TEST db across test cases and prevent such problem?

Thanks in advance

aboev
  • 332
  • 2
  • 9

2 Answers2

1

You should prepare and send request to node app inside a test and assert response there.

But it's not a good practice. The better solution would be HTTP mocks (like webmock gem). This approach will save lots of time in the future.

Alexander Shlenchack
  • 3,779
  • 6
  • 32
  • 46
  • Thanks for quick reply. I am sending request to node app inside rake test, as you mention. But I cannot send reply from node app to mocked http, so it goes back to a running rails server. I think data is lost at this point – aboev Dec 16 '15 at 12:17
  • You don't need to use a node app when using mocks. Please, see a good article about it: http://asquera.de/blog/2015-03-30/testing-external-apis-in-ruby/ – Alexander Shlenchack Dec 16 '15 at 12:21
0

Luckily, I figured out the solution.

By default, rake is wrapping all tests in separate DB transactions and rolls back on cleanup. Moreover, whatever requests/queries are coming outside of TestCase are not included in transaction and not visible inside the test case.

To avoid such behavior, we have to disable transactional fixtures in test/test_helper.rb

class ActiveSupport::TestCase
  self.use_transactional_fixtures = false
end

As downside, we have to cleanup test db manually. So @Alexander Shlenchack points out to avoid such practice in the first place and use http/socket mocks in future.

Community
  • 1
  • 1
aboev
  • 332
  • 2
  • 9