Methods
A
B
C
D
H
I
N
O
P
R
T
U
W
Included Modules
Classes and Modules
Constants
Fixture = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('Fixture', 'ActiveRecord::Fixture')
 

Fixtures are a way of organizing data that you want to test against; in short, sample data.

Fixture formats

Fixtures come in 1 flavor:

1.  YAML fixtures

YAML fixtures

This type of fixture is in YAML format and the preferred default. YAML is a file format which describes data structures in a non-verbose, human-readable format. It ships with Ruby 1.8.1+.

Unlike single-file fixtures, YAML fixtures are stored in a single file per model, which are placed in the directory appointed by ActiveSupport::TestCase.fixture_path=(path) (this is automatically configured for Rails, so you can just put your files in <your-rails-app>/test/fixtures/). The fixture file ends with the .yml file extension (Rails example: <your-rails-app>/test/fixtures/web_sites.yml). The format of a YAML fixture file looks like this:

rubyonrails:
  id: 1
  name: Ruby on Rails
  url: http://www.rubyonrails.org

google:
  id: 2
  name: Google
  url: http://www.google.com

This YAML fixture file includes two fixtures. Each YAML fixture (ie. record) is given a name and is followed by an indented list of key/value pairs in the “key: value” format. Records are separated by a blank line for your viewing pleasure.

Note that YAML fixtures are unordered. If you want ordered fixtures, use the omap YAML type. See yaml.org/type/omap.html for the specification. You will need ordered fixtures when you have foreign key constraints on keys in the same table. This is commonly needed for tree structures. Example:

--- !omap
- parent:
    id:         1
    parent_id:  NULL
    title:      Parent
- child:
    id:         2
    parent_id:  1
    title:      Child

Using fixtures in testcases

Since fixtures are a testing construct, we use them in our unit and functional tests. There are two ways to use the fixtures, but first let’s take a look at a sample unit test:

require 'test_helper'

class WebSiteTest < ActiveSupport::TestCase
  test "web_site_count" do
    assert_equal 2, WebSite.count
  end
end

By default, the test_helper module will load all of your fixtures into your test database, so this test will succeed. The testing environment will automatically load the all fixtures into the database before each test. To ensure consistent data, the environment deletes the fixtures before running the load.

In addition to being available in the database, the fixture’s data may also be accessed by using a special dynamic method, which has the same name as the model, and accepts the name of the fixture to instantiate:

test "find" do
  assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
end

Alternatively, you may enable auto-instantiation of the fixture data. For instance, take the following tests:

test "find_alt_method_1" do
  assert_equal "Ruby on Rails", @web_sites['rubyonrails']['name']
end

test "find_alt_method_2" do
  assert_equal "Ruby on Rails", @rubyonrails.news
end

In order to use these methods to access fixtured data within your testcases, you must specify one of the following in your ActiveSupport::TestCase-derived class:

  • to fully enable instantiated fixtures (enable alternate methods #1 and #2 above)

    self.use_instantiated_fixtures = true
  • create only the hash for the fixtures, do not ‘find’ each instance (enable alternate method #1 only)

    self.use_instantiated_fixtures = :no_instances

Using either of these alternate methods incurs a performance hit, as the fixtured data must be fully traversed in the database to create the fixture hash and/or instance variables. This is expensive for large sets of fixtured data.

Dynamic fixtures with ERB

Some times you don’t care about the content of the fixtures as much as you care about the volume. In these cases, you can mix ERB in with your YAML fixtures to create a bunch of fixtures for load testing, like:

<% for i in 1..1000 %>
fix_<%= i %>:
  id: <%= i %>
  name: guy_<%= 1 %>
<% end %>

This will create 1000 very simple YAML fixtures.

Using ERB, you can also inject dynamic values into your fixtures with inserts like <%= Date.today.strftime("%Y-%m-%d") %>. This is however a feature to be used with some caution. The point of fixtures are that they’re stable units of predictable sample data. If you feel that you need to inject dynamic values, then perhaps you should reexamine whether your application is properly testable. Hence, dynamic values in fixtures are to be considered a code smell.

Transactional fixtures

TestCases can use begin+rollback to isolate their changes to the database instead of having to delete+insert for every test case.

class FooTest < ActiveSupport::TestCase
  self.use_transactional_fixtures = true

  test "godzilla" do
    assert !Foo.find(:all).empty?
    Foo.destroy_all
    assert Foo.find(:all).empty?
  end

  test "godzilla aftermath" do
    assert !Foo.find(:all).empty?
  end
end

If you preload your test database with all fixture data (probably in the Rakefile task) and use transactional fixtures, then you may omit all fixtures declarations in your test cases since all the data’s already there and every case rolls back its changes.

In order to use instantiated fixtures with preloaded data, set self.pre_loaded_fixtures to true. This will provide access to fixture data for every table that has been loaded through fixtures (depending on the value of use_instantiated_fixtures)

When not to use transactional fixtures:

  1. You’re testing whether a transaction works correctly. Nested transactions don’t commit until all parent transactions commit, particularly, the fixtures transaction which is begun in setup and rolled back in teardown. Thus, you won’t be able to verify the results of your transaction until Active Record supports nested transactions or savepoints (in progress).

  2. Your database does not support transactions. Every Active Record database supports transactions except MySQL MyISAM. Use InnoDB, MaxDB, or NDB instead.

Advanced YAML Fixtures

YAML fixtures that don’t specify an ID get some extra features:

  • Stable, autogenerated IDs

  • Label references for associations (belongs_to, has_one, has_many)

  • HABTM associations as inline lists

  • Autofilled timestamp columns

  • Fixture label interpolation

  • Support for YAML defaults

Stable, autogenerated IDs

Here, have a monkey fixture:

george:
  id: 1
  name: George the Monkey

reginald:
  id: 2
  name: Reginald the Pirate

Each of these fixtures has two unique identifiers: one for the database and one for the humans. Why don’t we generate the primary key instead? Hashing each fixture’s label yields a consistent ID:

george: # generated id: 503576764
  name: George the Monkey

reginald: # generated id: 324201669
  name: Reginald the Pirate

Active Record looks at the fixture’s model class, discovers the correct primary key, and generates it right before inserting the fixture into the database.

The generated ID for a given label is constant, so we can discover any fixture’s ID without loading anything, as long as we know the label.

Label references for associations (belongs_to, has_one, has_many)

Specifying foreign keys in fixtures can be very fragile, not to mention difficult to read. Since Active Record can figure out the ID of any fixture from its label, you can specify FK’s by label instead of ID.

belongs_to

Let’s break out some more monkeys and pirates.

### in pirates.yml

reginald:
  id: 1
  name: Reginald the Pirate
  monkey_id: 1

### in monkeys.yml

george:
  id: 1
  name: George the Monkey
  pirate_id: 1

Add a few more monkeys and pirates and break this into multiple files, and it gets pretty hard to keep track of what’s going on. Let’s use labels instead of IDs:

### in pirates.yml

reginald:
  name: Reginald the Pirate
  monkey: george

### in monkeys.yml

george:
  name: George the Monkey
  pirate: reginald

Pow! All is made clear. Active Record reflects on the fixture’s model class, finds all the belongs_to associations, and allows you to specify a target label for the association (monkey: george) rather than a target id for the FK (monkey_id: 1).

Polymorphic belongs_to

Supporting polymorphic relationships is a little bit more complicated, since Active Record needs to know what type your association is pointing at. Something like this should look familiar:

### in fruit.rb

belongs_to :eater, :polymorphic => true

### in fruits.yml

apple:
  id: 1
  name: apple
  eater_id: 1
  eater_type: Monkey

Can we do better? You bet!

apple:
  eater: george (Monkey)

Just provide the polymorphic target type and Active Record will take care of the rest.

has_and_belongs_to_many

Time to give our monkey some fruit.

### in monkeys.yml

george:
  id: 1
  name: George the Monkey

### in fruits.yml

apple:
  id: 1
  name: apple

orange:
  id: 2
  name: orange

grape:
  id: 3
  name: grape

### in fruits_monkeys.yml

apple_george:
  fruit_id: 1
  monkey_id: 1

orange_george:
  fruit_id: 2
  monkey_id: 1

grape_george:
  fruit_id: 3
  monkey_id: 1

Let’s make the HABTM fixture go away.

### in monkeys.yml

george:
  id: 1
  name: George the Monkey
  fruits: apple, orange, grape

### in fruits.yml

apple:
  name: apple

orange:
  name: orange

grape:
  name: grape

Zap! No more fruits_monkeys.yml file. We’ve specified the list of fruits on George’s fixture, but we could’ve just as easily specified a list of monkeys on each fruit. As with belongs_to, Active Record reflects on the fixture’s model class and discovers the has_and_belongs_to_many associations.

Autofilled timestamp columns

If your table/model specifies any of Active Record’s standard timestamp columns (created_at, created_on, updated_at, updated_on), they will automatically be set to Time.now.

If you’ve set specific values, they’ll be left alone.

Fixture label interpolation

The label of the current fixture is always available as a column value:

geeksomnia:
  name: Geeksomnia's Account
  subdomain: $LABEL

Also, sometimes (like when porting older join table fixtures) you’ll need to be able to get a hold of the identifier for a given label. ERB to the rescue:

george_reginald:
  monkey_id: <%= ActiveRecord::Fixtures.identify(:reginald) %>
  pirate_id: <%= ActiveRecord::Fixtures.identify(:george) %>

Support for YAML defaults

You probably already know how to use YAML to set and reuse defaults in your database.yml file. You can use the same technique in your fixtures:

DEFAULTS: &DEFAULTS
  created_on: <%= 3.weeks.ago.to_s(:db) %>

first:
  name: Smurf
  <<: *DEFAULTS

second:
  name: Fraggle
  <<: *DEFAULTS

Any fixture labeled “DEFAULTS” is safely ignored.

Fixtures = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('Fixtures', 'ActiveRecord::Fixtures')
AbstractRequest = ActionController::Request = ActionDispatch::Request
AbstractResponse = ActionController::Response = ActionDispatch::Response
Routing = ActionDispatch::Routing
Integration = ActionDispatch::Integration
IntegrationTest = ActionDispatch::IntegrationTest
PerformanceTest = ActionDispatch::PerformanceTest
ALL = Mime::Type.new("*/*", :all, [])
HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess
MissingSourceFile = LoadError
RUBY_ENGINE = 'ruby' unless defined?(RUBY_ENGINE)
Instance Public methods
acts_like?(duck)

A duck-type assistant method. For example, Active Support extends Date to define an acts_like_date? method, and extends Time to define acts_like_time?. As a result, we can do “x.acts_like?(:time)” and “x.acts_like?(:date)” to do duck-type-safe comparisons, since classes that we want to act like Time simply need to define an acts_like_time? method.

# File activesupport/lib/active_support/core_ext/object/acts_like.rb, line 7
def acts_like?(duck)
  respond_to? :"acts_like_#{duck}?"
end
app(create=false)

reference the global “app” instance, created on demand. To recreate the instance, pass a non-false value as the parameter.

# File railties/lib/rails/console/app.rb, line 10
def app(create=false)
  @app_integration_instance = nil if create
  @app_integration_instance ||= new_session do |sess|
    sess.host! "www.example.com"
  end
end
blank?()

An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank.

This simplifies:

if address.nil? || address.empty?

…to:

if address.blank?
# File activesupport/lib/active_support/core_ext/object/blank.rb, line 12
def blank?
  respond_to?(:empty?) ? empty? : !self
end
controller()
# File railties/lib/rails/console/helpers.rb, line 5
def controller
  @controller ||= ApplicationController.new
end
create_fixtures(*table_names, &block)
# File railties/lib/rails/test_help.rb, line 42
def create_fixtures(*table_names, &block)
  Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block)
end
duplicable?()

Can you safely dup this object?

False for nil, false, true, symbols, numbers, class and module objects; true otherwise.

# File activesupport/lib/active_support/core_ext/object/duplicable.rb, line 24
def duplicable?
  true
end
helper()
# File railties/lib/rails/console/helpers.rb, line 1
def helper
  @helper ||= ApplicationController.helpers
end
html_safe?()
# File activesupport/lib/active_support/core_ext/string/output_safety.rb, line 65
def html_safe?
  false
end
in?(another_object)

Returns true if this object is included in the argument. Argument must be any object which responds to #include?. Usage:

characters = ["Konata", "Kagami", "Tsukasa"]
"Konata".in?(characters) # => true

This will throw an ArgumentError if the argument doesn’t respond to #include?.

# File activesupport/lib/active_support/core_ext/object/inclusion.rb, line 10
def in?(another_object)
  another_object.include?(self)
rescue NoMethodError
  raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
end
instance_variable_names()
# File activesupport/lib/active_support/core_ext/object/instance_variables.rb, line 27
def instance_variable_names
  instance_variables.map { |var| var.to_s }
end
new_session()

create a new session. If a block is given, the new session will be yielded to the block before being returned.

# File railties/lib/rails/console/app.rb, line 19
def new_session
  app = Rails.application
  session = ActionDispatch::Integration::Session.new(app)
  yield session if block_given?
  session
end
options()
# File railties/lib/rails/commands/profiler.rb, line 6
def options
  options = {}
  defaults = ActiveSupport::Testing::Performance::DEFAULTS

  OptionParser.new do |opt|
    opt.banner = "Usage: rails benchmarker 'Ruby.code' 'Ruby.more_code' ... [OPTS]"
    opt.on('-r', '--runs N', Numeric, 'Number of runs.', "Default: #{defaults[:runs]}") { |r| options[:runs] = r }
    opt.on('-o', '--output PATH', String, 'Directory to use when writing the results.', "Default: #{defaults[:output]}") { |o| options[:output] = o }
    opt.on('-m', '--metrics a,b,c', Array, 'Metrics to use.', "Default: #{defaults[:metrics].join(",")}") { |m| options[:metrics] = m.map(&:to_sym) }
    opt.on('-f', '--formats x,y,z', Array, 'Formats to output to.', "Default: #{defaults[:formats].join(",")}") { |m| options[:formats] = m.map(&:to_sym) }
    opt.parse!(ARGV)
  end

  options
end
presence()

Returns object if it’s present? otherwise returns nil. object.presence is equivalent to object.present? ? object : nil.

This is handy for any representation of objects where blank is the same as not present at all. For example, this simplifies a common check for HTTP POST/query parameters:

state   = params[:state]   if params[:state].present?
country = params[:country] if params[:country].present?
region  = state || country || 'US'

…becomes:

region = params[:state].presence || params[:country].presence || 'US'
# File activesupport/lib/active_support/core_ext/object/blank.rb, line 35
def presence
  self if present?
end
present?()

An object is present if it’s not blank?.

# File activesupport/lib/active_support/core_ext/object/blank.rb, line 17
def present?
  !blank?
end
reload!(print=true)

reloads the environment

# File railties/lib/rails/console/app.rb, line 27
def reload!(print=true)
  puts "Reloading..." if print
  ActionDispatch::Reloader.cleanup!
  ActionDispatch::Reloader.prepare!
  true
end
to_param()

Alias of to_s.

# File activesupport/lib/active_support/core_ext/object/to_param.rb, line 3
def to_param
  to_s
end
to_query(key)

Converts an object into a string suitable for use as a URL query string, using the given key as the param name.

Note: This method is defined as a default implementation for all Objects for Hash#to_query to work.

# File activesupport/lib/active_support/core_ext/object/to_query.rb, line 8
def to_query(key)
  require 'cgi' unless defined?(CGI) && defined?(CGI::escape)
  "#{CGI.escape(key.to_s)}=#{CGI.escape(to_param.to_s)}"
end
try(*a, &b)

Invokes the method identified by the symbol method, passing it any arguments and/or the block specified, just like the regular Ruby Object#send does.

Unlike that method however, a NoMethodError exception will not be raised and nil will be returned instead, if the receiving object is a nil object or NilClass.

If try is called without a method to call, it will yield any given block with the object.

Examples

Without try

@person && @person.name

or

@person ? @person.name : nil

With try

@person.try(:name)

try also accepts arguments and/or a block, for the method it is trying

Person.try(:find, 1)
@people.try(:collect) {|p| p.name}

Without a method argument try will yield to the block unless the receiver is nil.

@person.try { |p| "#{p.first_name} #{p.last_name}" }
# File activesupport/lib/active_support/core_ext/object/try.rb, line 28
def try(*a, &b)
  if a.empty? && block_given?
    yield self
  elsif !a.empty? && !respond_to?(a.first)
    nil
  else
    __send__(*a, &b)
  end
end
unescape(str, escaped = /%[a-fA-F\d]{2}/)
# File activesupport/lib/active_support/core_ext/uri.rb, line 12
def unescape(str, escaped = /%[a-fA-F\d]{2}/)
  # TODO: Are we actually sure that ASCII == UTF-8?
  # YK: My initial experiments say yes, but let's be sure please
  enc = str.encoding
  enc = Encoding::UTF_8 if enc == Encoding::US_ASCII
  str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(enc)
end
with_options(options)

An elegant way to factor duplication out of options passed to a series of method calls. Each method called in the block, with the block variable as the receiver, will have its options merged with the default options hash provided. Each method called on the block variable must take an options hash as its final argument.

Without with_options>, this code contains duplication:

class Account < ActiveRecord::Base
  has_many :customers, :dependent => :destroy
  has_many :products,  :dependent => :destroy
  has_many :invoices,  :dependent => :destroy
  has_many :expenses,  :dependent => :destroy
end

Using with_options, we can remove the duplication:

class Account < ActiveRecord::Base
  with_options :dependent => :destroy do |assoc|
    assoc.has_many :customers
    assoc.has_many :products
    assoc.has_many :invoices
    assoc.has_many :expenses
  end
end

It can also be used with an explicit receiver:

I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
  subject i18n.t :subject
  body    i18n.t :body, :user_name => user.name
end

with_options can also be nested since the call is forwarded to its receiver. Each nesting level will merge inherited defaults in addition to their own.

# File activesupport/lib/active_support/core_ext/object/with_options.rb, line 40
def with_options(options)
  yield ActiveSupport::OptionMerger.new(self, options)
end