mercredi 31 décembre 2014

Accessing Rails fixtures from test cases

Background


I have an application that pulls in data from various APIs into the local DB and then displays that data to the user. The API updates are scheduled via a rake task that run every X hours.


My testing involves two parts



  1. Units tests around pulling the data from the various APIs into the local DB

  2. Controller tests testing that the data in the DB is correctly picked up and manipulated for display by the Controller


For #1 I don't want any fixtures in the DB since the whole point is testing insertion into the DB in the first place. For #2 I do want to use fixtures.




The Issue


I don't want fixtures to be loaded for all tests, just certain sets of tests. By default, rails has each test require 'test_helper' which in turns (re-)creates fixtures by calling fixtures :all


To get around that, I created a custom method in test_helper.rb that creates fixtures that I can call when I want.



# test_helper.rb

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
# Added by Rails. Comment this out and replace with custom call below
# fixtures :all

def load_my_fixtures
# These are eventually called from each individual test that extends
# this class (ActiveSupport::TestCase) and inherits this method,
# so need to refer to methods and accessors explicitly
ActiveSupport::TestCase.fixtures :all

# Do other custom stuff
# ....

# Test output
# "one" is just a simple fixture I have I set up in employees.yml
puts employees(:one)
end
end


My employee_test.rb test case is straightforward



require 'test_helper'

class EmployeeTest < ActiveSupport::TestCase
test "the truth" do
load_my_fixtures
assert true
end
end


As per the rails documentation, each fixture is dumped into a local variable for easy access. However the call to employee(:one) above fails with



NoMethodError: undefined method `[]' for nil:NilClass




Questions



  1. The above error goes away if I uncomment the original fixtures :all at the top which loads all fixtures. Why is that?

  2. Is there an easy way to get a list of all fixtures (e.g. :one, :two, :three, etc..)? I don't want to hard-code the retrieval of all Employee fixtures

  3. Is there an easy way to manually clear the test DB? I know that while (re-)loading fixtures ActiveRecord already wipes the DB, but wondering how I can do it manually if needed.


Thanks for the help!


Aucun commentaire:

Enregistrer un commentaire