Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 915 lines (814 sloc) 29.894 kb
db045db David Heinemeier Hansson Initial
dhh authored
1 require 'erb'
2 require 'yaml'
87adecf Ken Collins Reimplement Fixtures.identify so that it consistently generates identiti...
metaskills authored
3 require 'zlib'
21901e9 Joshua Peek fixtures depends on dependencies
josh authored
4 require 'active_support/dependencies'
ad3f0ee Aaron Patterson adding AR::Fixtures::File class to wrap a fixture file
tenderlove authored
5 require 'active_record/fixtures/file'
b4115fd Aaron Patterson properly namespace the fixture exception
tenderlove authored
6 require 'active_record/errors'
88c3416 Jeremy Kemper r3581@sedna: jeremy | 2005-10-13 12:20:42 -0700
jeremy authored
7
b4115fd Aaron Patterson properly namespace the fixture exception
tenderlove authored
8 module ActiveRecord
77de690 Jeremy Kemper Be careful not to reference ActiveRecord if it isn't loaded, fixing rake...
jeremy authored
9 class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc:
10 end
2383a60 risk danger olson Allow set_fixture_class to take Classes instead of strings for a class i...
technoweenie authored
11
0a38e2a Xavier Noria restores the API docs of AR::Fixtures, made a quick pass over them, revi...
fxn authored
12 # \Fixtures are a way of organizing data that you want to test against; in short, sample data.
13 #
14 # They are stored in YAML files, one file per model, which are placed in the directory
15 # appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically
16 # configured for Rails, so you can just put your files in <tt><your-rails-app>/test/fixtures/</tt>).
17 # The fixture file ends with the <tt>.yml</tt> file extension (Rails example:
18 # <tt><your-rails-app>/test/fixtures/web_sites.yml</tt>). The format of a fixture file looks
19 # like this:
20 #
21 # rubyonrails:
22 # id: 1
23 # name: Ruby on Rails
24 # url: http://www.rubyonrails.org
25 #
26 # google:
27 # id: 2
28 # name: Google
29 # url: http://www.google.com
30 #
31 # This fixture file includes two fixtures. Each YAML fixture (ie. record) is given a name and
32 # is followed by an indented list of key/value pairs in the "key: value" format. Records are
33 # separated by a blank line for your viewing pleasure.
34 #
35 # Note that fixtures are unordered. If you want ordered fixtures, use the omap YAML type.
36 # See http://yaml.org/type/omap.html
37 # for the specification. You will need ordered fixtures when you have foreign key constraints
38 # on keys in the same table. This is commonly needed for tree structures. Example:
39 #
40 # --- !omap
41 # - parent:
42 # id: 1
43 # parent_id: NULL
44 # title: Parent
45 # - child:
46 # id: 2
47 # parent_id: 1
48 # title: Child
49 #
50 # = Using Fixtures in Test Cases
51 #
52 # Since fixtures are a testing construct, we use them in our unit and functional tests. There
53 # are two ways to use the fixtures, but first let's take a look at a sample unit test:
54 #
55 # require 'test_helper'
56 #
57 # class WebSiteTest < ActiveSupport::TestCase
58 # test "web_site_count" do
59 # assert_equal 2, WebSite.count
60 # end
61 # end
62 #
63 # By default, <tt>test_helper.rb</tt> will load all of your fixtures into your test database,
64 # so this test will succeed.
65 #
66 # The testing environment will automatically load the all fixtures into the database before each
67 # test. To ensure consistent data, the environment deletes the fixtures before running the load.
68 #
69 # In addition to being available in the database, the fixture's data may also be accessed by
70 # using a special dynamic method, which has the same name as the model, and accepts the
71 # name of the fixture to instantiate:
72 #
73 # test "find" do
74 # assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
75 # end
76 #
77 # Alternatively, you may enable auto-instantiation of the fixture data. For instance, take the
78 # following tests:
79 #
80 # test "find_alt_method_1" do
81 # assert_equal "Ruby on Rails", @web_sites['rubyonrails']['name']
82 # end
83 #
84 # test "find_alt_method_2" do
1f62b12 Geoffrey Roguelon Fix an error in example in methods of instanciated fixtures.
GRoguelon authored
85 # assert_equal "Ruby on Rails", @rubyonrails.name
0a38e2a Xavier Noria restores the API docs of AR::Fixtures, made a quick pass over them, revi...
fxn authored
86 # end
87 #
88 # In order to use these methods to access fixtured data within your testcases, you must specify one of the
89 # following in your <tt>ActiveSupport::TestCase</tt>-derived class:
90 #
91 # - to fully enable instantiated fixtures (enable alternate methods #1 and #2 above)
92 # self.use_instantiated_fixtures = true
93 #
94 # - create only the hash for the fixtures, do not 'find' each instance (enable alternate method #1 only)
95 # self.use_instantiated_fixtures = :no_instances
96 #
97 # Using either of these alternate methods incurs a performance hit, as the fixtured data must be fully
98 # traversed in the database to create the fixture hash and/or instance variables. This is expensive for
99 # large sets of fixtured data.
100 #
101 # = Dynamic fixtures with ERB
102 #
103 # Some times you don't care about the content of the fixtures as much as you care about the volume.
104 # In these cases, you can mix ERB in with your YAML fixtures to create a bunch of fixtures for load
105 # testing, like:
106 #
107 # <% 1.upto(1000) do |i| %>
108 # fix_<%= i %>:
109 # id: <%= i %>
110 # name: guy_<%= 1 %>
111 # <% end %>
112 #
113 # This will create 1000 very simple fixtures.
114 #
115 # Using ERB, you can also inject dynamic values into your fixtures with inserts like
116 # <tt><%= Date.today.strftime("%Y-%m-%d") %></tt>.
117 # This is however a feature to be used with some caution. The point of fixtures are that they're
118 # stable units of predictable sample data. If you feel that you need to inject dynamic values, then
119 # perhaps you should reexamine whether your application is properly testable. Hence, dynamic values
120 # in fixtures are to be considered a code smell.
121 #
122 # = Transactional Fixtures
123 #
124 # Test cases can use begin+rollback to isolate their changes to the database instead of having to
125 # delete+insert for every test case.
126 #
127 # class FooTest < ActiveSupport::TestCase
128 # self.use_transactional_fixtures = true
129 #
130 # test "godzilla" do
131 # assert !Foo.all.empty?
132 # Foo.destroy_all
133 # assert Foo.all.empty?
134 # end
135 #
136 # test "godzilla aftermath" do
137 # assert !Foo.all.empty?
138 # end
139 # end
140 #
141 # If you preload your test database with all fixture data (probably in the rake task) and use
142 # transactional fixtures, then you may omit all fixtures declarations in your test cases since
143 # all the data's already there and every case rolls back its changes.
144 #
145 # In order to use instantiated fixtures with preloaded data, set +self.pre_loaded_fixtures+ to
146 # true. This will provide access to fixture data for every table that has been loaded through
147 # fixtures (depending on the value of +use_instantiated_fixtures+).
148 #
149 # When *not* to use transactional fixtures:
150 #
151 # 1. You're testing whether a transaction works correctly. Nested transactions don't commit until
152 # all parent transactions commit, particularly, the fixtures transaction which is begun in setup
153 # and rolled back in teardown. Thus, you won't be able to verify
154 # the results of your transaction until Active Record supports nested transactions or savepoints (in progress).
155 # 2. Your database does not support transactions. Every Active Record database supports transactions except MySQL MyISAM.
156 # Use InnoDB, MaxDB, or NDB instead.
157 #
158 # = Advanced Fixtures
159 #
160 # Fixtures that don't specify an ID get some extra features:
161 #
162 # * Stable, autogenerated IDs
163 # * Label references for associations (belongs_to, has_one, has_many)
164 # * HABTM associations as inline lists
165 # * Autofilled timestamp columns
166 # * Fixture label interpolation
167 # * Support for YAML defaults
168 #
169 # == Stable, Autogenerated IDs
170 #
171 # Here, have a monkey fixture:
172 #
173 # george:
174 # id: 1
175 # name: George the Monkey
176 #
177 # reginald:
178 # id: 2
179 # name: Reginald the Pirate
180 #
181 # Each of these fixtures has two unique identifiers: one for the database
182 # and one for the humans. Why don't we generate the primary key instead?
183 # Hashing each fixture's label yields a consistent ID:
184 #
185 # george: # generated id: 503576764
186 # name: George the Monkey
187 #
188 # reginald: # generated id: 324201669
189 # name: Reginald the Pirate
190 #
191 # Active Record looks at the fixture's model class, discovers the correct
192 # primary key, and generates it right before inserting the fixture
193 # into the database.
194 #
195 # The generated ID for a given label is constant, so we can discover
196 # any fixture's ID without loading anything, as long as we know the label.
197 #
198 # == Label references for associations (belongs_to, has_one, has_many)
199 #
200 # Specifying foreign keys in fixtures can be very fragile, not to
201 # mention difficult to read. Since Active Record can figure out the ID of
202 # any fixture from its label, you can specify FK's by label instead of ID.
203 #
204 # === belongs_to
205 #
206 # Let's break out some more monkeys and pirates.
207 #
208 # ### in pirates.yml
209 #
210 # reginald:
211 # id: 1
212 # name: Reginald the Pirate
213 # monkey_id: 1
214 #
215 # ### in monkeys.yml
216 #
217 # george:
218 # id: 1
219 # name: George the Monkey
220 # pirate_id: 1
221 #
222 # Add a few more monkeys and pirates and break this into multiple files,
223 # and it gets pretty hard to keep track of what's going on. Let's
224 # use labels instead of IDs:
225 #
226 # ### in pirates.yml
227 #
228 # reginald:
229 # name: Reginald the Pirate
230 # monkey: george
231 #
232 # ### in monkeys.yml
233 #
234 # george:
235 # name: George the Monkey
236 # pirate: reginald
237 #
238 # Pow! All is made clear. Active Record reflects on the fixture's model class,
239 # finds all the +belongs_to+ associations, and allows you to specify
240 # a target *label* for the *association* (monkey: george) rather than
241 # a target *id* for the *FK* (<tt>monkey_id: 1</tt>).
242 #
243 # ==== Polymorphic belongs_to
244 #
245 # Supporting polymorphic relationships is a little bit more complicated, since
246 # Active Record needs to know what type your association is pointing at. Something
247 # like this should look familiar:
248 #
249 # ### in fruit.rb
250 #
251 # belongs_to :eater, :polymorphic => true
252 #
253 # ### in fruits.yml
254 #
255 # apple:
256 # id: 1
257 # name: apple
258 # eater_id: 1
259 # eater_type: Monkey
260 #
261 # Can we do better? You bet!
262 #
263 # apple:
264 # eater: george (Monkey)
265 #
266 # Just provide the polymorphic target type and Active Record will take care of the rest.
267 #
268 # === has_and_belongs_to_many
269 #
270 # Time to give our monkey some fruit.
271 #
272 # ### in monkeys.yml
273 #
274 # george:
275 # id: 1
276 # name: George the Monkey
277 #
278 # ### in fruits.yml
279 #
280 # apple:
281 # id: 1
282 # name: apple
283 #
284 # orange:
285 # id: 2
286 # name: orange
287 #
288 # grape:
289 # id: 3
290 # name: grape
291 #
292 # ### in fruits_monkeys.yml
293 #
294 # apple_george:
295 # fruit_id: 1
296 # monkey_id: 1
297 #
298 # orange_george:
299 # fruit_id: 2
300 # monkey_id: 1
301 #
302 # grape_george:
303 # fruit_id: 3
304 # monkey_id: 1
305 #
306 # Let's make the HABTM fixture go away.
307 #
308 # ### in monkeys.yml
309 #
310 # george:
311 # id: 1
312 # name: George the Monkey
313 # fruits: apple, orange, grape
314 #
315 # ### in fruits.yml
316 #
317 # apple:
318 # name: apple
319 #
320 # orange:
321 # name: orange
322 #
323 # grape:
324 # name: grape
325 #
326 # Zap! No more fruits_monkeys.yml file. We've specified the list of fruits
327 # on George's fixture, but we could've just as easily specified a list
328 # of monkeys on each fruit. As with +belongs_to+, Active Record reflects on
329 # the fixture's model class and discovers the +has_and_belongs_to_many+
330 # associations.
331 #
332 # == Autofilled Timestamp Columns
333 #
334 # If your table/model specifies any of Active Record's
335 # standard timestamp columns (+created_at+, +created_on+, +updated_at+, +updated_on+),
336 # they will automatically be set to <tt>Time.now</tt>.
337 #
338 # If you've set specific values, they'll be left alone.
339 #
340 # == Fixture label interpolation
341 #
342 # The label of the current fixture is always available as a column value:
343 #
344 # geeksomnia:
345 # name: Geeksomnia's Account
346 # subdomain: $LABEL
347 #
348 # Also, sometimes (like when porting older join table fixtures) you'll need
349 # to be able to get a hold of the identifier for a given label. ERB
350 # to the rescue:
351 #
352 # george_reginald:
353 # monkey_id: <%= ActiveRecord::Fixtures.identify(:reginald) %>
354 # pirate_id: <%= ActiveRecord::Fixtures.identify(:george) %>
355 #
356 # == Support for YAML defaults
357 #
358 # You probably already know how to use YAML to set and reuse defaults in
359 # your <tt>database.yml</tt> file. You can use the same technique in your fixtures:
360 #
361 # DEFAULTS: &DEFAULTS
362 # created_on: <%= 3.weeks.ago.to_s(:db) %>
363 #
364 # first:
365 # name: Smurf
366 # *DEFAULTS
367 #
368 # second:
369 # name: Fraggle
370 # *DEFAULTS
371 #
372 # Any fixture labeled "DEFAULTS" is safely ignored.
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
373 class Fixtures
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
374 #--
375 # NOTE: an instance of Fixtures can be called fixture_set, it is normally stored in a single YAML file and possibly in a folder with the same name.
376 #++
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
377 MAX_ID = 2 ** 30 - 1
c758955 David Heinemeier Hansson Tidied up Fixtures for better readability and some error checking [bitsw...
dhh authored
378
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
379 @@all_cached_fixtures = Hash.new { |h,k| h[k] = {} }
b095ce6 Jeremy Kemper Fixtures test fixes and general cleanup. Closes #9682 [norbert]
jeremy authored
380
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
381 def self.default_fixture_model_name(fixture_set_name) # :nodoc:
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
382 ActiveRecord::Base.pluralize_table_names ?
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
383 fixture_set_name.singularize.camelize :
384 fixture_set_name.camelize
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
385 end
fb09d02 Aaron Patterson refactor fixtures to do less work in the constructor
tenderlove authored
386
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
387 def self.default_fixture_table_name(fixture_set_name) # :nodoc:
388 "#{ ActiveRecord::Base.table_name_prefix }"\
389 "#{ fixture_set_name.tr('/', '_') }"\
390 "#{ ActiveRecord::Base.table_name_suffix }".to_sym
7162ea2 Alexey Muranov Fixture's table name be defined in the model
alexeymuranov authored
391 end
392
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
393 def self.reset_cache
394 @@all_cached_fixtures.clear
395 end
b095ce6 Jeremy Kemper Fixtures test fixes and general cleanup. Closes #9682 [norbert]
jeremy authored
396
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
397 def self.cache_for_connection(connection)
398 @@all_cached_fixtures[connection]
399 end
b095ce6 Jeremy Kemper Fixtures test fixes and general cleanup. Closes #9682 [norbert]
jeremy authored
400
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
401 def self.fixture_is_cached?(connection, table_name)
402 cache_for_connection(connection)[table_name]
403 end
078bd05 David Heinemeier Hansson Added fixture caching thatll speed up a normal fixture-powered test suit...
dhh authored
404
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
405 def self.cached_fixtures(connection, keys_to_fetch = nil)
406 if keys_to_fetch
407 cache_for_connection(connection).values_at(*keys_to_fetch)
408 else
409 cache_for_connection(connection).values
410 end
078bd05 David Heinemeier Hansson Added fixture caching thatll speed up a normal fixture-powered test suit...
dhh authored
411 end
412
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
413 def self.cache_fixtures(connection, fixtures_map)
414 cache_for_connection(connection).update(fixtures_map)
415 end
b095ce6 Jeremy Kemper Fixtures test fixes and general cleanup. Closes #9682 [norbert]
jeremy authored
416
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
417 def self.instantiate_fixtures(object, fixture_set, load_instances = true)
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
418 if load_instances
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
419 fixture_set.each do |fixture_name, fixture|
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
420 begin
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
421 object.instance_variable_set "@#{fixture_name}", fixture.find
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
422 rescue FixtureClassNotFound
423 nil
424 end
b2cfbc4 David Heinemeier Hansson Added with additional settings for working with transactional fixtures a...
dhh authored
425 end
9b0fd9d David Heinemeier Hansson Added that the 'fixture :posts' syntax can be used for has_and_belongs_t...
dhh authored
426 end
db045db David Heinemeier Hansson Initial
dhh authored
427 end
a2f0ae7 Jeremy Kemper r2718@asus: jeremy | 2005-10-23 14:45:30 -0700
jeremy authored
428
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
429 def self.instantiate_all_loaded_fixtures(object, load_instances = true)
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
430 all_loaded_fixtures.each_value do |fixture_set|
431 instantiate_fixtures(object, fixture_set, load_instances)
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
432 end
f8783ab David Heinemeier Hansson Made eager loading work even more
dhh authored
433 end
b095ce6 Jeremy Kemper Fixtures test fixes and general cleanup. Closes #9682 [norbert]
jeremy authored
434
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
435 cattr_accessor :all_loaded_fixtures
436 self.all_loaded_fixtures = {}
c758955 David Heinemeier Hansson Tidied up Fixtures for better readability and some error checking [bitsw...
dhh authored
437
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
438 def self.create_fixtures(fixtures_directory, fixture_set_names, class_names = {})
439 fixture_set_names = Array(fixture_set_names).map(&:to_s)
78372b6 Jeremy Kemper create_fixtures should accept symbol keys for custom table -> class mapp...
jeremy authored
440 class_names = class_names.stringify_keys
87b7b5b David Heinemeier Hansson Added fixtures :all to test_helper.rb to assume that most people just wa...
dhh authored
441
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
442 # FIXME: Apparently JK uses this.
443 connection = block_given? ? yield : ActiveRecord::Base.connection
b095ce6 Jeremy Kemper Fixtures test fixes and general cleanup. Closes #9682 [norbert]
jeremy authored
444
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
445 files_to_read = fixture_set_names.reject { |fs_name|
446 fixture_is_cached?(connection, fs_name)
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
447 }
87b7b5b David Heinemeier Hansson Added fixtures :all to test_helper.rb to assume that most people just wa...
dhh authored
448
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
449 unless files_to_read.empty?
450 connection.disable_referential_integrity do
451 fixtures_map = {}
87b7b5b David Heinemeier Hansson Added fixtures :all to test_helper.rb to assume that most people just wa...
dhh authored
452
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
453 fixture_sets = files_to_read.map do |fs_name|
454 fixtures_map[fs_name] = new( # ActiveRecord::Fixtures.new
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
455 connection,
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
456 fs_name,
457 class_names[fs_name] || default_fixture_model_name(fs_name),
458 ::File.join(fixtures_directory, fs_name))
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
459 end
87b7b5b David Heinemeier Hansson Added fixtures :all to test_helper.rb to assume that most people just wa...
dhh authored
460
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
461 all_loaded_fixtures.update(fixtures_map)
c758955 David Heinemeier Hansson Tidied up Fixtures for better readability and some error checking [bitsw...
dhh authored
462
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
463 connection.transaction(:requires_new => true) do
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
464 fixture_sets.each do |fs|
465 conn = fs.model_class.respond_to?(:connection) ? fs.model_class.connection : connection
466 table_rows = fs.table_rows
a2f0ae7 Jeremy Kemper r2718@asus: jeremy | 2005-10-23 14:45:30 -0700
jeremy authored
467
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
468 table_rows.keys.each do |table|
469 conn.delete "DELETE FROM #{conn.quote_table_name(table)}", 'Fixture Delete'
470 end
fd81c70 Aaron Patterson extract database activity out of Fixtures instances
tenderlove authored
471
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
472 table_rows.each do |fixture_set_name, rows|
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
473 rows.each do |row|
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
474 conn.insert_fixture(row, fixture_set_name)
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
475 end
49eafd8 Jeremy Kemper Foxy fixtures. Adapter#disable_referential_integrity. Closes #9981.
jeremy authored
476 end
078bd05 David Heinemeier Hansson Added fixture caching thatll speed up a normal fixture-powered test suit...
dhh authored
477 end
b095ce6 Jeremy Kemper Fixtures test fixes and general cleanup. Closes #9682 [norbert]
jeremy authored
478
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
479 # Cap primary key sequences to max(pk).
480 if connection.respond_to?(:reset_pk_sequence!)
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
481 fixture_sets.each do |fs|
482 connection.reset_pk_sequence!(fs.table_name)
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
483 end
078bd05 David Heinemeier Hansson Added fixture caching thatll speed up a normal fixture-powered test suit...
dhh authored
484 end
a2f0ae7 Jeremy Kemper r2718@asus: jeremy | 2005-10-23 14:45:30 -0700
jeremy authored
485 end
77a6e25 Aaron Patterson use hash defaults to dry up ||= calls
tenderlove authored
486
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
487 cache_fixtures(connection, fixtures_map)
488 end
7117fdb Jeremy Kemper r3616@asus: jeremy | 2005-09-26 23:09:28 -0700
jeremy authored
489 end
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
490 cached_fixtures(connection, fixture_set_names)
a2f0ae7 Jeremy Kemper r2718@asus: jeremy | 2005-10-23 14:45:30 -0700
jeremy authored
491 end
492
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
493 # Returns a consistent, platform-independent identifier for +label+.
494 # Identifiers are positive integers less than 2^32.
495 def self.identify(label)
496 Zlib.crc32(label.to_s) % MAX_ID
0ebbf6b Aaron Patterson calculate model class on construction
tenderlove authored
497 end
498
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
499 attr_reader :table_name, :name, :fixtures, :model_class
79e85ed David Heinemeier Hansson Added reverse order of deleting fixtures, so referential keys can be mai...
dhh authored
500
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
501 def initialize(connection, name, class_name, path)
502 @fixtures = {} # Ordered hash
503 @name = name
504 @path = path
83dd6e1 Aaron Patterson favor composition over inheritence. use AS::OrderedHash rather than omap
tenderlove authored
505
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
506 if class_name.is_a?(Class) # TODO: Should be an AR::Base type class, or any?
7162ea2 Alexey Muranov Fixture's table name be defined in the model
alexeymuranov authored
507 @model_class = class_name
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
508 else
7162ea2 Alexey Muranov Fixture's table name be defined in the model
alexeymuranov authored
509 @model_class = class_name.constantize rescue nil
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
510 end
83dd6e1 Aaron Patterson favor composition over inheritence. use AS::OrderedHash rather than omap
tenderlove authored
511
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
512 @connection = ( model_class.respond_to?(:connection) ?
513 model_class.connection : connection )
7162ea2 Alexey Muranov Fixture's table name be defined in the model
alexeymuranov authored
514
515 @table_name = ( model_class.respond_to?(:table_name) ?
516 model_class.table_name :
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
517 self.class.default_fixture_table_name(name) )
7162ea2 Alexey Muranov Fixture's table name be defined in the model
alexeymuranov authored
518
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
519 read_fixture_files
520 end
79e85ed David Heinemeier Hansson Added reverse order of deleting fixtures, so referential keys can be mai...
dhh authored
521
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
522 def [](x)
523 fixtures[x]
524 end
49eafd8 Jeremy Kemper Foxy fixtures. Adapter#disable_referential_integrity. Closes #9981.
jeremy authored
525
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
526 def []=(k,v)
527 fixtures[k] = v
528 end
49eafd8 Jeremy Kemper Foxy fixtures. Adapter#disable_referential_integrity. Closes #9981.
jeremy authored
529
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
530 def each(&block)
531 fixtures.each(&block)
532 end
49eafd8 Jeremy Kemper Foxy fixtures. Adapter#disable_referential_integrity. Closes #9981.
jeremy authored
533
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
534 def size
535 fixtures.size
536 end
49eafd8 Jeremy Kemper Foxy fixtures. Adapter#disable_referential_integrity. Closes #9981.
jeremy authored
537
0034b78 Sebastian Martinez Remove extra white spaces on ActiveRecord docs.
smartinez87 authored
538 # Return a hash of rows to be inserted. The key is the table, the value is
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
539 # a list of rows to insert to that table.
540 def table_rows
541 now = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now
542 now = now.to_s(:db)
49eafd8 Jeremy Kemper Foxy fixtures. Adapter#disable_referential_integrity. Closes #9981.
jeremy authored
543
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
544 # allow a standard key to be used for doing defaults in YAML
545 fixtures.delete('DEFAULTS')
49eafd8 Jeremy Kemper Foxy fixtures. Adapter#disable_referential_integrity. Closes #9981.
jeremy authored
546
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
547 # track any join tables we need to insert later
548 rows = Hash.new { |h,table| h[table] = [] }
49eafd8 Jeremy Kemper Foxy fixtures. Adapter#disable_referential_integrity. Closes #9981.
jeremy authored
549
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
550 rows[table_name] = fixtures.map do |label, fixture|
551 row = fixture.to_hash
552
6498695 Jon Leighton Fixtures support for ActiveRecord::Model
jonleighton authored
553 if model_class && model_class < ActiveRecord::Model
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
554 # fill in timestamp columns if they aren't specified and the model is set to record_timestamps
555 if model_class.record_timestamps
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
556 timestamp_column_names.each do |c_name|
557 row[c_name] = now unless row.key?(c_name)
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
558 end
c7e3969 Jeremy Kemper Foxy fixtures: support single-table inheritance. Closes #10234.
jeremy authored
559 end
560
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
561 # interpolate the fixture label
562 row.each do |key, value|
563 row[key] = label if value == "$LABEL"
564 end
8b3f831 Jeremy Kemper Foxy fixtures: allow mixed usage to make migration easier and more attra...
jeremy authored
565
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
566 # generate a primary key if necessary
567 if has_primary_key_column? && !row.include?(primary_key_name)
568 row[primary_key_name] = ActiveRecord::Fixtures.identify(label)
569 end
c95f066 Michael Koziarski Add 'foxy' support for fixtures of polymorphic associations. Closes #101...
NZKoz authored
570
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
571 # If STI is used, find the correct subclass for association reflection
572 reflection_class =
573 if row.include?(inheritance_column_name)
574 row[inheritance_column_name].constantize rescue model_class
575 else
576 model_class
49eafd8 Jeremy Kemper Foxy fixtures. Adapter#disable_referential_integrity. Closes #9981.
jeremy authored
577 end
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
578
579 reflection_class.reflect_on_all_associations.each do |association|
580 case association.macro
581 when :belongs_to
582 # Do not replace association name with association foreign key if they are named the same
583 fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s
584
585 if association.name.to_s != fk_name && value = row.delete(association.name.to_s)
586 if association.options[:polymorphic] && value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
587 # support polymorphic belongs_to as "label (Type)"
588 row[association.foreign_type] = $1
589 end
590
591 row[fk_name] = ActiveRecord::Fixtures.identify(value)
592 end
593 when :has_and_belongs_to_many
594 if (targets = row.delete(association.name.to_s))
595 targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
4649294 Andrew White Improve the derivation of HABTM assocation join table names
pixeltrix authored
596 table_name = association.join_table
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
597 rows[table_name].concat targets.map { |target|
598 { association.foreign_key => row[primary_key_name],
599 association.association_foreign_key => ActiveRecord::Fixtures.identify(target) }
600 }
601 end
49eafd8 Jeremy Kemper Foxy fixtures. Adapter#disable_referential_integrity. Closes #9981.
jeremy authored
602 end
603 end
604 end
605
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
606 row
607 end
608 rows
49eafd8 Jeremy Kemper Foxy fixtures. Adapter#disable_referential_integrity. Closes #9981.
jeremy authored
609 end
610
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
611 private
612 def primary_key_name
6474765 Jon Leighton Revert "Raise error on unknown primary key."
jonleighton authored
613 @primary_key_name ||= model_class && model_class.primary_key
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
614 end
8b3f831 Jeremy Kemper Foxy fixtures: allow mixed usage to make migration easier and more attra...
jeremy authored
615
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
616 def has_primary_key_column?
617 @has_primary_key_column ||= primary_key_name &&
618 model_class.columns.any? { |c| c.name == primary_key_name }
619 end
49eafd8 Jeremy Kemper Foxy fixtures. Adapter#disable_referential_integrity. Closes #9981.
jeremy authored
620
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
621 def timestamp_column_names
622 @timestamp_column_names ||=
623 %w(created_at created_on updated_at updated_on) & column_names
624 end
c7e3969 Jeremy Kemper Foxy fixtures: support single-table inheritance. Closes #10234.
jeremy authored
625
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
626 def inheritance_column_name
627 @inheritance_column_name ||= model_class && model_class.inheritance_column
628 end
49eafd8 Jeremy Kemper Foxy fixtures. Adapter#disable_referential_integrity. Closes #9981.
jeremy authored
629
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
630 def column_names
631 @column_names ||= @connection.columns(@table_name).collect { |c| c.name }
db045db David Heinemeier Hansson Initial
dhh authored
632 end
633
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
634 def read_fixture_files
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
635 yaml_files = Dir["#{@path}/**/*.yml"].select { |f|
1716da0 Aaron Patterson removing CSV fixture support
tenderlove authored
636 ::File.file?(f)
637 } + [yaml_file_path]
638
639 yaml_files.each do |file|
640 Fixtures::File.open(file) do |fh|
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
641 fh.each do |fixture_name, row|
642 fixtures[fixture_name] = ActiveRecord::Fixture.new(row, model_class)
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
643 end
b095ce6 Jeremy Kemper Fixtures test fixes and general cleanup. Closes #9682 [norbert]
jeremy authored
644 end
645 end
646 end
c758955 David Heinemeier Hansson Tidied up Fixtures for better readability and some error checking [bitsw...
dhh authored
647
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
648 def yaml_file_path
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
649 "#{@path}.yml"
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
650 end
5e3eaff David Heinemeier Hansson Added CSV format for fixtures #272 [what-a-day]
dhh authored
651
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
652 end
db045db David Heinemeier Hansson Initial
dhh authored
653
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
654 class Fixture #:nodoc:
655 include Enumerable
b095ce6 Jeremy Kemper Fixtures test fixes and general cleanup. Closes #9682 [norbert]
jeremy authored
656
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
657 class FixtureError < StandardError #:nodoc:
658 end
b095ce6 Jeremy Kemper Fixtures test fixes and general cleanup. Closes #9682 [norbert]
jeremy authored
659
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
660 class FormatError < FixtureError #:nodoc:
661 end
db045db David Heinemeier Hansson Initial
dhh authored
662
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
663 attr_reader :model_class, :fixture
33e96f3 Jeremy Kemper Oracle binary fixtures; pull fixture insertion into the adapters. Closes...
jeremy authored
664
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
665 def initialize(fixture, model_class)
666 @fixture = fixture
667 @model_class = model_class
668 end
83f6559 Jeremy Kemper Prefer to instantiate fixtures with model classes instead of their names...
jeremy authored
669
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
670 def class_name
671 model_class.name if model_class
672 end
db045db David Heinemeier Hansson Initial
dhh authored
673
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
674 def each
675 fixture.each { |item| yield item }
676 end
db045db David Heinemeier Hansson Initial
dhh authored
677
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
678 def [](key)
679 fixture[key]
680 end
db045db David Heinemeier Hansson Initial
dhh authored
681
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
682 alias :to_hash :fixture
c758955 David Heinemeier Hansson Tidied up Fixtures for better readability and some error checking [bitsw...
dhh authored
683
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
684 def find
685 if model_class
686 model_class.find(fixture[model_class.primary_key])
687 else
688 raise FixtureClassNotFound, "No class attached to find."
689 end
9b0fd9d David Heinemeier Hansson Added that the 'fixture :posts' syntax can be used for has_and_belongs_t...
dhh authored
690 end
db045db David Heinemeier Hansson Initial
dhh authored
691 end
692 end
693
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
694 module ActiveRecord
695 module TestFixtures
4e50a35 Joshua Peek Break up DependencyModule's dual function of providing a "depend_on" DSL...
josh authored
696 extend ActiveSupport::Concern
a2875be Bryan Helmkamp Use DependencyModule for included hooks in ActiveRecord
brynary authored
697
698 included do
699 setup :setup_fixtures
700 teardown :teardown_fixtures
701
d8db571 Neeraj Singh replacing superclass_delegating_accessor with class_attribute
neerajdotname authored
702 class_attribute :fixture_path
703 class_attribute :fixture_table_names
704 class_attribute :fixture_class_names
705 class_attribute :use_transactional_fixtures
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
706 class_attribute :use_instantiated_fixtures # true, false, or :no_instances
d8db571 Neeraj Singh replacing superclass_delegating_accessor with class_attribute
neerajdotname authored
707 class_attribute :pre_loaded_fixtures
a2875be Bryan Helmkamp Use DependencyModule for included hooks in ActiveRecord
brynary authored
708
709 self.fixture_table_names = []
894ce15 Use better defaults for fixtures: transactional=true, instantiated=false
Jeffrey Hardy authored
710 self.use_transactional_fixtures = true
711 self.use_instantiated_fixtures = false
a2875be Bryan Helmkamp Use DependencyModule for included hooks in ActiveRecord
brynary authored
712 self.pre_loaded_fixtures = false
87b7b5b David Heinemeier Hansson Added fixtures :all to test_helper.rb to assume that most people just wa...
dhh authored
713
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
714 self.fixture_class_names = Hash.new do |h, fixture_set_name|
715 h[fixture_set_name] = ActiveRecord::Fixtures.default_fixture_model_name(fixture_set_name)
fb09d02 Aaron Patterson refactor fixtures to do less work in the constructor
tenderlove authored
716 end
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
717 end
718
719 module ClassMethods
e0ef093 Alexey Muranov Use foo/bar instead of foo_bar keys for fixtures
alexeymuranov authored
720 # Sets the model class for a fixture when the class name cannot be inferred from the fixture name.
721 #
722 # Examples:
723 #
724 # set_fixture_class :some_fixture => SomeModel,
725 # 'namespaced/fixture' => Another::Model
726 #
727 # The keys must be the fixture names, that coincide with the short paths to the fixture files.
728 #--
729 # It is also possible to pass the class name instead of the class:
730 # set_fixture_class 'some_fixture' => 'SomeModel'
731 # I think this option is redundant, i propose to deprecate it.
732 # Isn't it easier to always pass the class itself?
733 # (2011-12-20 alexeymuranov)
734 #++
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
735 def set_fixture_class(class_names = {})
e0ef093 Alexey Muranov Use foo/bar instead of foo_bar keys for fixtures
alexeymuranov authored
736 self.fixture_class_names = self.fixture_class_names.merge(class_names.stringify_keys)
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
737 end
bc1aa7d David Heinemeier Hansson fixtures :models will now also attempt to include the model.rb file
dhh authored
738
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
739 def fixtures(*fixture_set_names)
740 if fixture_set_names.first == :all
741 fixture_set_names = Dir["#{fixture_path}/**/*.yml"].map { |f|
00c5342 Aaron Patterson use File.basename to get the filename minus .yml
tenderlove authored
742 File.basename f, '.yml'
743 }
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
744 else
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
745 fixture_set_names = fixture_set_names.flatten.map { |n| n.to_s }
139b924 Jeremy Kemper * Continue evolution toward ActiveSupport::TestCase and friends. #10679...
jeremy authored
746 end
747
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
748 self.fixture_table_names |= fixture_set_names
749 require_fixture_classes(fixture_set_names)
750 setup_fixture_accessors(fixture_set_names)
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
751 end
752
753 def try_to_load_dependency(file_name)
754 require_dependency file_name
755 rescue LoadError => e
756 # Let's hope the developer has included it himself
3b0e1d9 Joshua Peek Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
757
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
758 # Let's warn in case this is a subdependency, otherwise
759 # subdependency error messages are totally cryptic
760 if ActiveRecord::Base.logger
761 ActiveRecord::Base.logger.warn("Unable to load #{file_name}, underlying cause #{e.message} \n\n #{e.backtrace.join("\n")}")
fbf41c7 David Heinemeier Hansson Added logging for dependency load errors with fixtures (closes #11056) [...
dhh authored
762 end
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
763 end
3b0e1d9 Joshua Peek Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
764
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
765 def require_fixture_classes(fixture_set_names = nil)
766 if fixture_set_names
767 fixture_set_names = fixture_set_names.map { |n| n.to_s }
768 else
769 fixture_set_names = fixture_table_names
770 end
771
772 fixture_set_names.each do |file_name|
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
773 file_name = file_name.singularize if ActiveRecord::Base.pluralize_table_names
774 try_to_load_dependency(file_name)
f389a8f David Heinemeier Hansson Updated and added more documentation
dhh authored
775 end
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
776 end
c758955 David Heinemeier Hansson Tidied up Fixtures for better readability and some error checking [bitsw...
dhh authored
777
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
778 def setup_fixture_accessors(fixture_set_names = nil)
779 fixture_set_names = Array(fixture_set_names || fixture_table_names)
8276a24 Aaron Patterson fixture methods can be overridden and super() is useful
tenderlove authored
780 methods = Module.new do
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
781 fixture_set_names.each do |fs_name|
782 fs_name = fs_name.to_s
783 accessor_name = fs_name.tr('/', '_').to_sym
673daea Jeremy Kemper Fixtures: people(:technomancy, :josh) returns both fixtures. Closes #788...
jeremy authored
784
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
785 define_method(accessor_name) do |*fixture_names|
786 force_reload = fixture_names.pop if fixture_names.last == true || fixture_names.last == :reload
23e24c5 David Heinemeier Hansson Setting fixtures automatically for integration tests is a bit harder -- ...
dhh authored
787
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
788 @fixture_cache[fs_name] ||= {}
23e24c5 David Heinemeier Hansson Setting fixtures automatically for integration tests is a bit harder -- ...
dhh authored
789
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
790 instances = fixture_names.map do |f_name|
791 f_name = f_name.to_s
792 @fixture_cache[fs_name].delete(f_name) if force_reload
673daea Jeremy Kemper Fixtures: people(:technomancy, :josh) returns both fixtures. Closes #788...
jeremy authored
793
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
794 if @loaded_fixtures[fs_name][f_name]
795 @fixture_cache[fs_name][f_name] ||= @loaded_fixtures[fs_name][f_name].find
8276a24 Aaron Patterson fixture methods can be overridden and super() is useful
tenderlove authored
796 else
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
797 raise StandardError, "No fixture named '#{f_name}' found for fixture set '#{fs_name}'"
ce66bfd Marcin Raczkowski IdentityMap - misc fixes
swistak authored
798 end
673daea Jeremy Kemper Fixtures: people(:technomancy, :josh) returns both fixtures. Closes #788...
jeremy authored
799 end
6d9ee4a Jamis Buck Added fixture accessors that can be used when fixture instantiation is d...
jamis authored
800
8276a24 Aaron Patterson fixture methods can be overridden and super() is useful
tenderlove authored
801 instances.size == 1 ? instances.first : instances
802 end
b52d9d0 Alexey Muranov Fixes for TestFixtures::setup_fixture_accessors
alexeymuranov authored
803 private accessor_name
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
804 end
139b924 Jeremy Kemper * Continue evolution toward ActiveSupport::TestCase and friends. #10679...
jeremy authored
805 end
8276a24 Aaron Patterson fixture methods can be overridden and super() is useful
tenderlove authored
806 include methods
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
807 end
2c0fa32 Jamis Buck Do not use instantiated fixtures (in general) in tests. Also, support th...
jamis authored
808
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
809 def uses_transaction(*methods)
810 @uses_transaction = [] unless defined?(@uses_transaction)
a7eb8d9 Prem Sichanugrist Removing most of the symbol to proc usage in Active Record
sikachu authored
811 @uses_transaction.concat methods.map { |m| m.to_s }
2c0fa32 Jamis Buck Do not use instantiated fixtures (in general) in tests. Also, support th...
jamis authored
812 end
813
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
814 def uses_transaction?(method)
815 @uses_transaction = [] unless defined?(@uses_transaction)
816 @uses_transaction.include?(method.to_s)
2c0fa32 Jamis Buck Do not use instantiated fixtures (in general) in tests. Also, support th...
jamis authored
817 end
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
818 end
2c0fa32 Jamis Buck Do not use instantiated fixtures (in general) in tests. Also, support th...
jamis authored
819
ad93212 Jeremy Kemper Rename use_transactional_fixtures? so it doesn't collide with the superc...
jeremy authored
820 def run_in_transaction?
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
821 use_transactional_fixtures &&
822 !self.class.uses_transaction?(method_name)
823 end
5b866f7 Jeremy Kemper r4720@asus: jeremy | 2006-06-28 18:12:57 -0700
jeremy authored
824
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
825 def setup_fixtures
2ec6ef5 Piotr Sarnacki Change unless + ! into if
drogus authored
826 return if ActiveRecord::Base.configurations.blank?
b2cfbc4 David Heinemeier Hansson Added with additional settings for working with transactional fixtures a...
dhh authored
827
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
828 if pre_loaded_fixtures && !use_transactional_fixtures
829 raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_fixtures'
830 end
17d3fd3 Jeremy Kemper r2736@asus: jeremy | 2005-10-24 17:08:12 -0700
jeremy authored
831
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
832 @fixture_cache = {}
d102791 Aaron Patterson ensure @fixture_connections is initialized in case an exception happens ...
tenderlove authored
833 @fixture_connections = []
d9f460a Pratik Ensure @@already_loaded_fixtures is initialized before use
lifo authored
834 @@already_loaded_fixtures ||= {}
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
835
836 # Load fixtures once and begin transaction.
ad93212 Jeremy Kemper Rename use_transactional_fixtures? so it doesn't collide with the superc...
jeremy authored
837 if run_in_transaction?
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
838 if @@already_loaded_fixtures[self.class]
839 @loaded_fixtures = @@already_loaded_fixtures[self.class]
903ef71 David Heinemeier Hansson Added transactional fixtures that uses rollback to undo changes to fixtu...
dhh authored
840 else
e0802fa Aaron Patterson avoid side effects from method calls, localize ivar assignment
tenderlove authored
841 @loaded_fixtures = load_fixtures
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
842 @@already_loaded_fixtures[self.class] = @loaded_fixtures
903ef71 David Heinemeier Hansson Added transactional fixtures that uses rollback to undo changes to fixtu...
dhh authored
843 end
999b7ed Jeremy Kemper Transactional fixtures enlist all active database connections.
jeremy authored
844 @fixture_connections = enlist_fixture_connections
845 @fixture_connections.each do |connection|
846 connection.increment_open_transactions
847 connection.transaction_joinable = false
848 connection.begin_db_transaction
849 end
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
850 # Load fixtures for every test.
851 else
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
852 ActiveRecord::Fixtures.reset_cache
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
853 @@already_loaded_fixtures[self.class] = nil
e0802fa Aaron Patterson avoid side effects from method calls, localize ivar assignment
tenderlove authored
854 @loaded_fixtures = load_fixtures
903ef71 David Heinemeier Hansson Added transactional fixtures that uses rollback to undo changes to fixtu...
dhh authored
855 end
856
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
857 # Instantiate fixtures for every test if requested.
858 instantiate_fixtures if use_instantiated_fixtures
859 end
860
861 def teardown_fixtures
862 return unless defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
5b866f7 Jeremy Kemper r4720@asus: jeremy | 2006-06-28 18:12:57 -0700
jeremy authored
863
ad93212 Jeremy Kemper Rename use_transactional_fixtures? so it doesn't collide with the superc...
jeremy authored
864 unless run_in_transaction?
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
865 ActiveRecord::Fixtures.reset_cache
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
866 end
b095ce6 Jeremy Kemper Fixtures test fixes and general cleanup. Closes #9682 [norbert]
jeremy authored
867
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
868 # Rollback changes if a transaction is active.
999b7ed Jeremy Kemper Transactional fixtures enlist all active database connections.
jeremy authored
869 if run_in_transaction?
870 @fixture_connections.each do |connection|
871 if connection.open_transactions != 0
872 connection.rollback_db_transaction
873 connection.decrement_open_transactions
874 end
875 end
876 @fixture_connections.clear
db045db David Heinemeier Hansson Initial
dhh authored
877 end
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
878 ActiveRecord::Base.clear_active_connections!
879 end
c758955 David Heinemeier Hansson Tidied up Fixtures for better readability and some error checking [bitsw...
dhh authored
880
999b7ed Jeremy Kemper Transactional fixtures enlist all active database connections.
jeremy authored
881 def enlist_fixture_connections
882 ActiveRecord::Base.connection_handler.connection_pools.values.map(&:connection)
883 end
884
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
885 private
886 def load_fixtures
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
887 fixtures = ActiveRecord::Fixtures.create_fixtures(fixture_path, fixture_table_names, fixture_class_names)
e0802fa Aaron Patterson avoid side effects from method calls, localize ivar assignment
tenderlove authored
888 Hash[fixtures.map { |f| [f.name, f] }]
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
889 end
03097d3 David Heinemeier Hansson Fixed that fixtures were being deleted in the same order as inserts caus...
dhh authored
890
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
891 # for pre_loaded_fixtures, only require the classes once. huge speed improvement
892 @@required_fixture_classes = false
03097d3 David Heinemeier Hansson Fixed that fixtures were being deleted in the same order as inserts caus...
dhh authored
893
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
894 def instantiate_fixtures
895 if pre_loaded_fixtures
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
896 raise RuntimeError, 'Load fixtures before instantiating them.' if ActiveRecord::Fixtures.all_loaded_fixtures.empty?
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
897 unless @@required_fixture_classes
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
898 self.class.require_fixture_classes ActiveRecord::Fixtures.all_loaded_fixtures.keys
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
899 @@required_fixture_classes = true
900 end
7db2ef4 Jason Noble Namespace Fixtures in ActiveRecord
jasonnoble authored
901 ActiveRecord::Fixtures.instantiate_all_loaded_fixtures(self, load_instances?)
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
902 else
903 raise RuntimeError, 'Load fixtures before instantiating them.' if @loaded_fixtures.nil?
12ceb45 Alexey Muranov Rename some variables
alexeymuranov authored
904 @loaded_fixtures.each_value do |fixture_set|
905 ActiveRecord::Fixtures.instantiate_fixtures(self, fixture_set, load_instances?)
903ef71 David Heinemeier Hansson Added transactional fixtures that uses rollback to undo changes to fixtu...
dhh authored
906 end
f389a8f David Heinemeier Hansson Updated and added more documentation
dhh authored
907 end
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
908 end
03097d3 David Heinemeier Hansson Fixed that fixtures were being deleted in the same order as inserts caus...
dhh authored
909
b0ee1bd Jeremy Kemper Remove fixtures from Test::Unit::TestCase. Mix in AR::TestFixtures inste...
jeremy authored
910 def load_instances?
911 use_instantiated_fixtures != :no_instances
912 end
f389a8f David Heinemeier Hansson Updated and added more documentation
dhh authored
913 end
daf3e92 David Heinemeier Hansson Added a db2 adapter that only depends on the Ruby/DB2 bindings (http://r...
dhh authored
914 end
Something went wrong with that request. Please try again.