Search code examples
ruby-on-railsnode.jsunit-testingactiverecordrake

ActiveRecord data loss when unit testing Rails + Node.js


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


Solution

  • 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.