3 require 'models/binary'
5 require 'models/computer'
6 require 'models/developer'
7 require 'models/company'
11 require 'models/course'
12 require 'models/category'
13 require 'models/parrot'
14 require 'models/pirate'
15 require 'models/treasure'
16 require 'models/matey'
20 class FixturesTest
< ActiveRecord
::TestCase
21 self.use_instantiated_fixtures
= true
22 self.use_transactional_fixtures
= false
24 fixtures
:topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries
26 FIXTURES
= %w( accounts binaries companies customers
27 developers developers_projects entrants
28 movies projects subscribers topics tasks
)
29 MATCH_ATTRIBUTE_NAME
= /[a-zA-Z][-_\w]*/
31 def test_clean_fixtures
32 FIXTURES
.each
do |name
|
34 assert_nothing_raised
{ fixtures
= create_fixtures(name
) }
35 assert_kind_of(Fixtures
, fixtures
)
36 fixtures
.each
{ |name
, fixture
|
37 fixture
.each
{ |key
, value
|
38 assert_match(MATCH_ATTRIBUTE_NAME
, key
)
44 def test_multiple_clean_fixtures
46 assert_nothing_raised
{ fixtures_array
= create_fixtures(*FIXTURES
) }
47 assert_kind_of(Array
, fixtures_array
)
48 fixtures_array
.each
{ |fixtures
| assert_kind_of(Fixtures
, fixtures
) }
52 topics
= create_fixtures("topics")
53 assert_equal("The First Topic", topics
["first"]["title"])
54 assert_nil(topics
["second"]["author_email_address"])
58 topics
= create_fixtures("topics")
59 first_row
= ActiveRecord
::Base.connection
.select_one("SELECT * FROM topics WHERE author_name = 'David'")
60 assert_equal("The First Topic", first_row
["title"])
62 second_row
= ActiveRecord
::Base.connection
.select_one("SELECT * FROM topics WHERE author_name = 'Mary'")
63 assert_nil(second_row
["author_email_address"])
66 if ActiveRecord
::Base.connection
.supports_migrations
?
67 def test_inserts_with_pre_and_suffix
68 # Reset cache to make finds on the new table work
71 ActiveRecord
::Base.connection
.create_table
:prefix_topics_suffix do |t
|
72 t
.column
:title, :string
73 t
.column
:author_name, :string
74 t
.column
:author_email_address, :string
75 t
.column
:written_on, :datetime
76 t
.column
:bonus_time, :time
77 t
.column
:last_read, :date
78 t
.column
:content, :string
79 t
.column
:approved, :boolean, :default => true
80 t
.column
:replies_count, :integer, :default => 0
81 t
.column
:parent_id, :integer
82 t
.column
:type, :string, :limit => 50
85 # Store existing prefix/suffix
86 old_prefix
= ActiveRecord
::Base.table_name_prefix
87 old_suffix
= ActiveRecord
::Base.table_name_suffix
89 # Set a prefix/suffix we can test against
90 ActiveRecord
::Base.table_name_prefix
= 'prefix_'
91 ActiveRecord
::Base.table_name_suffix
= '_suffix'
93 topics
= create_fixtures("topics")
95 first_row
= ActiveRecord
::Base.connection
.select_one("SELECT * FROM prefix_topics_suffix WHERE author_name = 'David'")
96 assert_equal("The First Topic", first_row
["title"])
98 second_row
= ActiveRecord
::Base.connection
.select_one("SELECT * FROM prefix_topics_suffix WHERE author_name = 'Mary'")
99 assert_nil(second_row
["author_email_address"])
101 # This checks for a caching problem which causes a bug in the fixtures
102 # class-level configuration helper.
103 assert_not_nil topics
, "Fixture data inserted, but fixture objects not returned from create"
105 # Restore prefix/suffix to its previous values
106 ActiveRecord
::Base.table_name_prefix
= old_prefix
107 ActiveRecord
::Base.table_name_suffix
= old_suffix
109 ActiveRecord
::Base.connection
.drop_table
:prefix_topics_suffix rescue nil
113 def test_insert_with_datetime
114 topics
= create_fixtures("tasks")
119 def test_logger_level_invariant
120 level
= ActiveRecord
::Base.logger
.level
121 create_fixtures('topics')
122 assert_equal level
, ActiveRecord
::Base.logger
.level
125 def test_instantiation
126 topics
= create_fixtures("topics")
127 assert_kind_of Topic
, topics
["first"].find
130 def test_complete_instantiation
131 assert_equal
4, @topics.size
132 assert_equal
"The First Topic", @first.title
135 def test_fixtures_from_root_yml_with_instantiation
136 # assert_equal 2, @accounts.size
137 assert_equal
50, @unknown.credit_limit
140 def test_erb_in_fixtures
141 assert_equal
11, @developers.size
142 assert_equal
"fixture_5", @dev_5.name
145 def test_empty_yaml_fixture
146 assert_not_nil Fixtures
.new( Account
.connection
, "accounts", 'Account', FIXTURES_ROOT
+ "/naked/yml/accounts")
149 def test_empty_yaml_fixture_with_a_comment_in_it
150 assert_not_nil Fixtures
.new( Account
.connection
, "companies", 'Company', FIXTURES_ROOT
+ "/naked/yml/companies")
153 def test_dirty_dirty_yaml_file
154 assert_raises(Fixture
::FormatError) do
155 Fixtures
.new( Account
.connection
, "courses", 'Course', FIXTURES_ROOT
+ "/naked/yml/courses")
159 def test_empty_csv_fixtures
160 assert_not_nil Fixtures
.new( Account
.connection
, "accounts", 'Account', FIXTURES_ROOT
+ "/naked/csv/accounts")
163 def test_omap_fixtures
164 assert_nothing_raised
do
165 fixtures
= Fixtures
.new(Account
.connection
, 'categories', 'Category', FIXTURES_ROOT
+ "/categories_ordered")
168 fixtures
.each
do |name
, fixture
|
169 assert_equal
"fixture_no_#{i}", name
170 assert_equal
"Category #{i}", fixture
['name']
176 def test_yml_file_in_subdirectory
177 assert_equal(categories(:sub_special_1).name
, "A special category in a subdir file")
178 assert_equal(categories(:sub_special_1).class, SpecialCategory
)
181 def test_subsubdir_file_with_arbitrary_name
182 assert_equal(categories(:sub_special_3).name
, "A special category in an arbitrarily named subsubdir file")
183 assert_equal(categories(:sub_special_3).class, SpecialCategory
)
186 def test_binary_in_fixtures
187 assert_equal
1, @binaries.size
188 data = File
.read(ASSETS_ROOT
+ "/flowers.jpg")
189 data.force_encoding('ASCII-8BIT') if data.respond_to
?(:force_encoding)
191 assert_equal
data, @flowers.data
195 if Account
.connection
.respond_to
?(:reset_pk_sequence!)
196 class FixturesResetPkSequenceTest
< ActiveRecord
::TestCase
201 @instances = [Account
.new(:credit_limit => 50), Company
.new(:name => 'RoR Consulting')]
202 Fixtures
.reset_cache
# make sure tables get reinitialized
205 def test_resets_to_min_pk_with_specified_pk_and_sequence
206 @instances.each
do |instance
|
207 model
= instance
.class
209 model
.connection
.reset_pk_sequence
!(model
.table_name
, model
.primary_key
, model
.sequence_name
)
212 assert_equal
1, instance
.id
, "Sequence reset for #{model.table_name} failed."
216 def test_resets_to_min_pk_with_default_pk_and_sequence
217 @instances.each
do |instance
|
218 model
= instance
.class
220 model
.connection
.reset_pk_sequence
!(model
.table_name
)
223 assert_equal
1, instance
.id
, "Sequence reset for #{model.table_name} failed."
227 def test_create_fixtures_resets_sequences_when_not_cached
228 @instances.each
do |instance
|
229 max_id
= create_fixtures(instance
.class.table_name
).inject(0) do |max_id
, (name
, fixture
)|
230 fixture_id
= fixture
['id'].to_i
231 fixture_id
> max_id
? fixture_id
: max_id
234 # Clone the last fixture to check that it gets the next greatest id.
236 assert_equal max_id
+ 1, instance
.id
, "Sequence reset for #{instance.class.table_name} failed."
242 class FixturesWithoutInstantiationTest
< ActiveRecord
::TestCase
243 self.use_instantiated_fixtures
= false
244 fixtures
:topics, :developers, :accounts
246 def test_without_complete_instantiation
249 assert_nil
@developers
253 def test_fixtures_from_root_yml_without_instantiation
257 def test_accessor_methods
258 assert_equal
"The First Topic", topics(:first).title
259 assert_equal
"Jamis", developers(:jamis).name
260 assert_equal
50, accounts(:signals37).credit_limit
263 def test_accessor_methods_with_multiple_args
264 assert_equal
2, topics(:first, :second).size
265 assert_raise(StandardError
) { topics([:first, :second]) }
268 uses_mocha
'reloading_fixtures_through_accessor_methods' do
269 def test_reloading_fixtures_through_accessor_methods
270 assert_equal
"The First Topic", topics(:first).title
271 @loaded_fixtures['topics']['first'].expects(:find).returns(stub(:title => "Fresh Topic!"))
272 assert_equal
"Fresh Topic!", topics(:first, true).title
277 class FixturesWithoutInstanceInstantiationTest
< ActiveRecord
::TestCase
278 self.use_instantiated_fixtures
= true
279 self.use_instantiated_fixtures
= :no_instances
281 fixtures
:topics, :developers, :accounts
283 def test_without_instance_instantiation
285 assert_not_nil
@topics
286 assert_not_nil
@developers
287 assert_not_nil
@accounts
291 class TransactionalFixturesTest
< ActiveRecord
::TestCase
292 self.use_instantiated_fixtures
= true
293 self.use_transactional_fixtures
= true
298 assert_not_nil
@first
302 def test_destroy_just_kidding
303 assert_not_nil
@first
307 class MultipleFixturesTest
< ActiveRecord
::TestCase
309 fixtures
:developers, :accounts
311 def test_fixture_table_names
312 assert_equal
%w(topics developers accounts
), fixture_table_names
316 class SetupTest
< ActiveRecord
::TestCase
327 class SetupSubclassTest
< SetupTest
333 def test_subclassing_should_preserve_setups
340 class OverlappingFixturesTest
< ActiveRecord
::TestCase
341 fixtures
:topics, :developers
342 fixtures
:developers, :accounts
344 def test_fixture_table_names
345 assert_equal
%w(topics developers accounts
), fixture_table_names
349 class ForeignKeyFixturesTest
< ActiveRecord
::TestCase
350 fixtures
:fk_test_has_pk, :fk_test_has_fk
352 # if foreign keys are implemented and fixtures
353 # are not deleted in reverse order then this test
354 # case will raise StatementInvalid
365 class CheckSetTableNameFixturesTest
< ActiveRecord
::TestCase
366 set_fixture_class
:funny_jokes => 'Joke'
367 fixtures
:funny_jokes
368 # Set to false to blow away fixtures cache and ensure our fixtures are loaded
369 # and thus takes into account our set_fixture_class
370 self.use_transactional_fixtures
= false
372 def test_table_method
373 assert_kind_of Joke
, funny_jokes(:a_joke)
377 class FixtureNameIsNotTableNameFixturesTest
< ActiveRecord
::TestCase
378 set_fixture_class
:items => Book
380 # Set to false to blow away fixtures cache and ensure our fixtures are loaded
381 # and thus takes into account our set_fixture_class
382 self.use_transactional_fixtures
= false
384 def test_named_accessor
385 assert_kind_of Book
, items(:dvd)
389 class FixtureNameIsNotTableNameMultipleFixturesTest
< ActiveRecord
::TestCase
390 set_fixture_class
:items => Book
, :funny_jokes => Joke
391 fixtures
:items, :funny_jokes
392 # Set to false to blow away fixtures cache and ensure our fixtures are loaded
393 # and thus takes into account our set_fixture_class
394 self.use_transactional_fixtures
= false
396 def test_named_accessor_of_differently_named_fixture
397 assert_kind_of Book
, items(:dvd)
400 def test_named_accessor_of_same_named_fixture
401 assert_kind_of Joke
, funny_jokes(:a_joke)
405 class CustomConnectionFixturesTest
< ActiveRecord
::TestCase
406 set_fixture_class
:courses => Course
408 # Set to false to blow away fixtures cache and ensure our fixtures are loaded
409 # and thus takes into account our set_fixture_class
410 self.use_transactional_fixtures
= false
413 assert_kind_of Course
, courses(:ruby)
414 assert_equal Course
.connection
, courses(:ruby).connection
418 class InvalidTableNameFixturesTest
< ActiveRecord
::TestCase
419 fixtures
:funny_jokes
420 # Set to false to blow away fixtures cache and ensure our fixtures are loaded
421 # and thus takes into account our lack of set_fixture_class
422 self.use_transactional_fixtures
= false
424 def test_raises_error
425 assert_raises FixtureClassNotFound
do
431 class CheckEscapedYamlFixturesTest
< ActiveRecord
::TestCase
432 set_fixture_class
:funny_jokes => 'Joke'
433 fixtures
:funny_jokes
434 # Set to false to blow away fixtures cache and ensure our fixtures are loaded
435 # and thus takes into account our set_fixture_class
436 self.use_transactional_fixtures
= false
438 def test_proper_escaped_fixture
439 assert_equal
"The \\n Aristocrats\nAte the candy\n", funny_jokes(:another_joke).name
443 class DevelopersProject
; end
444 class ManyToManyFixturesWithClassDefined
< ActiveRecord
::TestCase
445 fixtures
:developers_projects
447 def test_this_should_run_cleanly
452 class FixturesBrokenRollbackTest
< ActiveRecord
::TestCase
454 alias_method
:ar_setup_fixtures, :setup_fixtures
455 alias_method
:setup_fixtures, :blank_setup
456 alias_method
:setup, :blank_setup
458 def blank_teardown
; end
459 alias_method
:ar_teardown_fixtures, :teardown_fixtures
460 alias_method
:teardown_fixtures, :blank_teardown
461 alias_method
:teardown, :blank_teardown
463 def test_no_rollback_in_teardown_unless_transaction_active
464 assert_equal
0, ActiveRecord
::Base.connection
.open_transactions
465 assert_raise(RuntimeError
) { ar_setup_fixtures
}
466 assert_equal
0, ActiveRecord
::Base.connection
.open_transactions
467 assert_nothing_raised
{ ar_teardown_fixtures
}
468 assert_equal
0, ActiveRecord
::Base.connection
.open_transactions
477 class LoadAllFixturesTest
< ActiveRecord
::TestCase
478 self.fixture_path
= FIXTURES_ROOT
+ "/all"
482 assert_equal
%w(developers people tasks
), fixture_table_names
.sort
486 class FasterFixturesTest
< ActiveRecord
::TestCase
487 fixtures
:categories, :authors
489 def load_extra_fixture(name
)
490 fixture
= create_fixtures(name
)
491 assert fixture
.is_a
?(Fixtures
)
492 @loaded_fixtures[fixture
.table_name
] = fixture
496 assert Fixtures
.fixture_is_cached
?(ActiveRecord
::Base.connection
, 'categories')
497 assert Fixtures
.fixture_is_cached
?(ActiveRecord
::Base.connection
, 'authors')
500 create_fixtures('categories')
501 create_fixtures('authors')
504 load_extra_fixture('posts')
505 assert Fixtures
.fixture_is_cached
?(ActiveRecord
::Base.connection
, 'posts')
506 self.class.setup_fixture_accessors('posts')
507 assert_equal
'Welcome to the weblog', posts(:welcome).title
511 class FoxyFixturesTest
< ActiveRecord
::TestCase
512 fixtures
:parrots, :parrots_pirates, :pirates, :treasures, :mateys, :ships, :computers, :developers
514 def test_identifies_strings
515 assert_equal(Fixtures
.identify("foo"), Fixtures
.identify("foo"))
516 assert_not_equal(Fixtures
.identify("foo"), Fixtures
.identify("FOO"))
519 def test_identifies_symbols
520 assert_equal(Fixtures
.identify(:foo), Fixtures
.identify(:foo))
523 TIMESTAMP_COLUMNS
= %w(created_at created_on updated_at updated_on
)
525 def test_populates_timestamp_columns
526 TIMESTAMP_COLUMNS
.each
do |property
|
527 assert_not_nil(parrots(:george).send(property
), "should set #{property}")
531 def test_does_not_populate_timestamp_columns_if_model_has_set_record_timestamps_to_false
532 TIMESTAMP_COLUMNS
.each
do |property
|
533 assert_nil(ships(:black_pearl).send(property
), "should not set #{property}")
537 def test_populates_all_columns_with_the_same_time
540 TIMESTAMP_COLUMNS
.each
do |property
|
541 current
= parrots(:george).send(property
)
544 assert_equal(last
, current
)
549 def test_only_populates_columns_that_exist
550 assert_not_nil(pirates(:blackbeard).created_on
)
551 assert_not_nil(pirates(:blackbeard).updated_on
)
554 def test_preserves_existing_fixture_data
555 assert_equal(2.weeks
.ago
.to_date
, pirates(:redbeard).created_on
.to_date
)
556 assert_equal(2.weeks
.ago
.to_date
, pirates(:redbeard).updated_on
.to_date
)
559 def test_generates_unique_ids
560 assert_not_nil(parrots(:george).id
)
561 assert_not_equal(parrots(:george).id
, parrots(:louis).id
)
564 def test_automatically_sets_primary_key
565 assert_not_nil(ships(:black_pearl))
568 def test_preserves_existing_primary_key
569 assert_equal(2, ships(:interceptor).id
)
572 def test_resolves_belongs_to_symbols
573 assert_equal(parrots(:george), pirates(:blackbeard).parrot
)
576 def test_ignores_belongs_to_symbols_if_association_and_foreign_key_are_named_the_same
577 assert_equal(developers(:david), computers(:workstation).developer
)
580 def test_supports_join_tables
581 assert(pirates(:blackbeard).parrots
.include?(parrots(:george)))
582 assert(pirates(:blackbeard).parrots
.include?(parrots(:louis)))
583 assert(parrots(:george).pirates
.include?(pirates(:blackbeard)))
586 def test_supports_inline_habtm
587 assert(parrots(:george).treasures
.include?(treasures(:diamond)))
588 assert(parrots(:george).treasures
.include?(treasures(:sapphire)))
589 assert(!parrots(:george).treasures
.include?(treasures(:ruby)))
592 def test_supports_inline_habtm_with_specified_id
593 assert(parrots(:polly).treasures
.include?(treasures(:ruby)))
594 assert(parrots(:polly).treasures
.include?(treasures(:sapphire)))
595 assert(!parrots(:polly).treasures
.include?(treasures(:diamond)))
598 def test_supports_yaml_arrays
599 assert(parrots(:louis).treasures
.include?(treasures(:diamond)))
600 assert(parrots(:louis).treasures
.include?(treasures(:sapphire)))
603 def test_strips_DEFAULTS_key
604 assert_raise(StandardError
) { parrots(:DEFAULTS) }
606 # this lets us do YAML defaults and not have an extra fixture entry
607 %w(sapphire ruby
).each
{ |t
| assert(parrots(:davey).treasures
.include?(treasures(t
))) }
610 def test_supports_label_interpolation
611 assert_equal("frederick", parrots(:frederick).name
)
614 def test_supports_polymorphic_belongs_to
615 assert_equal(pirates(:redbeard), treasures(:sapphire).looter
)
616 assert_equal(parrots(:louis), treasures(:ruby).looter
)
619 def test_only_generates_a_pk_if_necessary
620 m
= Matey
.find(:first)
621 m
.pirate
= pirates(:blackbeard)
622 m
.target
= pirates(:redbeard)
625 def test_supports_sti
626 assert_kind_of DeadParrot
, parrots(:polly)
627 assert_equal
pirates(:blackbeard), parrots(:polly).killer
631 class ActiveSupportSubclassWithFixturesTest
< ActiveRecord
::TestCase
634 # This seemingly useless assertion catches a bug that caused the fixtures
635 # setup code call nil[]
637 assert_equal
parrots(:louis), Parrot
.find_by_name("King Louis")
641 class FixtureLoadingTest
< ActiveRecord
::TestCase
642 uses_mocha
'reloading_fixtures_through_accessor_methods' do
643 def test_logs_message_for_failed_dependency_load
644 Test
::Unit::TestCase.expects(:require_dependency).with(:does_not_exist).raises(LoadError
)
645 ActiveRecord
::Base.logger
.expects(:warn)
646 Test
::Unit::TestCase.try_to_load_dependency(:does_not_exist)
649 def test_does_not_logs_message_for_successful_dependency_load
650 Test
::Unit::TestCase.expects(:require_dependency).with(:works_out_fine)
651 ActiveRecord
::Base.logger
.expects(:warn).never
652 Test
::Unit::TestCase.try_to_load_dependency(:works_out_fine)