Here we have sample Ruby on Rails fixture file:
tenant_newsletter: name: sample text_message: hello phone_number: 0555444332211 first_name: foo last_name: bar
There are two popular ways to use fixtures in your Rails tests. The first one is directly calling the name of fixture file followed by a symbol stating the name of any individual fixture, ie:
class NewsletterTest < ActiveSupport::TestCase test 'a sample test' do assert newsletters(:tenant_newsletter).valid? end end
However, sometimes developers tend to assign individual fixtures to an instance variable in
setup block though, ie:
class NewsletterTest < ActiveSupport::TestCase setup do @tenant_newsletter = newsletters(:tenant_newsletter) end test 'a sample test' do assert @tenant_newsletter.valid? end end
When you would like to stick with instance variables, there is one more way to define them, instantiated fixtures:
class NewsletterTest < ActiveSupport::TestCase self.use_instantiated_fixtures = true test 'a sample test' do assert @tenant_newsletter.valid? end end
instantiated_fixtures automatically creates instance variables for each fixture item, and fixture items become accessible as instance variables with the same name. Imagine a more populated fixture like this:
city: name: Samsun country: name: Turkey region: name: Black Sea
when you enable
instantiated_fixtures you will automatically have three different instance variables as
@region. These instance variables will immediately be accessible from anywhere in your test file.
This behavior might be handy for some cases but please be aware of the risk of conflicting variables! Let say you prefer to use 'easy to remember' names for your fixture items, as shown as 'city', 'country', 'region' etc. Since
instantiated_fixtures will give you an instance variable for each item, you must be sure that you don't use these names anywhere in your test files, in order to prevent possible conflict and confusion.