How do I actually use real, pre-existing Rails fixtures, the same as
the unit tests use? For familiarity?
What I was missing is the regular use of fixtures as in rspec or test
unit, like so:
u = users(:bob)
u.email = “aaa”
u.should_not be_valid
This link
http://wiki.github.com/aslakhellesoy/cucumber/fixtures
described how to get fixtures loaded for the entire suite, so that you
can say:
u = User.find(1)
or
u = User.find_by_name(“Bob”)
this is kind of a drag, if you have a well formed fixture file with
symbolic names, etc.
So I came up with this (which was developed and tested in Cucumber gem
version 0.2.3, and I haven’t tried it yet with the latest 0.3.9):
Add this to your env file:
Fixtures.reset_cache
fixtures_folder = File.join(RAILS_ROOT, ‘test’, ‘fixtures’)
fixtures = Dir[File.join(fixtures_folder, ‘.yml’)].map {|f|
File.basename(f, ‘.yml’) }
fixtures << Dir[File.join(fixtures_folder, '.csv’)].map {|f|
File.basename(f, ‘.csv’) }
If your fixture files are named differently from the classes they
refer to,
you also need to do this:
class_table_mappings = {:table_name_in_db => class_name}
Fixtures.create_fixtures(fixtures_folder, fixtures,
class_table_mappings)
otherwise:
This will populate the test database tables
Fixtures.create_fixtures(fixtures_folder, fixtures)
The following will define methods that can access symbolic fixture
names,
as in users(:bob)
World do |world|
(class << world; self; end).class_eval do
@@fixture_cache = {}
fixtures.each do |table_name|
table_name = table_name.to_s.tr(‘.’, ‘_’)
define_method(table_name) do |*fixture_symbols|
@@fixture_cache[table_name] ||= {}
instances = fixture_symbols.map do |fixture_symbol|
if fix =
Fixtures.cached_fixtures(ActiveRecord::Base.connection,
table_name)[fixture_symbol.to_s]
@@fixture_cache[table_name][fixture_symbol] ||= fix.find #
find model.find’s the instance
else
raise StandardError, “No fixture with name
‘#{fixture_symbol}’ found for table ‘#{table_name}’”
end
end
instances.size == 1 ? instances.first : instances
end
end
end
world
end