A Guide to Testing Rails Applications¶ ↑
This guide covers built-in mechanisms in Rails for testing your application.
After reading this guide, you will know:
-
Rails testing terminology.
-
How to write unit, functional, and integration tests for your application.
-
Other popular testing approaches and plugins.
Why Write Tests for your Rails Applications?¶ ↑
Rails makes it super easy to write your tests. It starts by producing skeleton test code while you are creating your models and controllers.
By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
Introduction to Testing¶ ↑
Testing support was woven into the Rails fabric from the beginning. It wasn't an “oh! let's bolt on support for running tests because they're new and cool” epiphany. Just about every Rails application interacts heavily with a database and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
The Test Environment¶ ↑
By default, every Rails application has three environments: development,
test, and production. The database for each one of them is configured in
config/database.yml
.
A dedicated test database allows you to set up and interact with test data in isolation. Tests can mangle test data with confidence, that won't touch the data in the development or production databases.
Rails Sets up for Testing from the Word Go¶ ↑
Rails creates a test
folder for you as soon as you create a
Rails project using rails new
application_name. If
you list the contents of this folder then you shall see:
$ ls -F test controllers/ helpers/ mailers/ test_helper.rb fixtures/ integration/ models/
The models
directory is meant to hold tests for your models,
the controllers
directory is meant to hold tests for your
controllers and the integration
directory is meant to hold
tests that involve any number of controllers interacting.
Fixtures are a way of organizing test data; they reside in the
fixtures
folder.
The test_helper.rb
file holds the default configuration for
your tests.
The Low-Down on Fixtures¶ ↑
For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures. You can find comprehensive documentation in the fixture api documentation.
What Are Fixtures?¶ ↑
Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent written in YAML. There is one file per model.
You'll find fixtures under your test/fixtures
directory.
When you run rails generate model
to create a new model
fixture stubs will be automatically created and placed in this directory.
YAML¶ ↑
YAML-formatted fixtures are a very human-friendly way to describe your
sample data. These types of fixtures have the .yml file
extension (as in users.yml
).
Here's a sample YAML fixture file:
# lo & behold! I am a YAML comment! david: name: David Heinemeier Hansson birthday: 1979-10-15 profession: Systems development steve: name: Steve Ross Kellock birthday: 1974-09-27 profession: guy with keyboard
Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are typically separated by a blank space. You can place comments in a fixture file by using the # character in the first column. Keys which resemble YAML keywords such as 'yes' and 'no' are quoted so that the YAML Parser correctly interprets them.
If you are working with associations, you can simply define a
reference node between two different fixtures. Here's an example with a
belongs_to
/has_many
association:
# In fixtures/categories.yml about: name: About # In fixtures/articles.yml one: title: Welcome to Rails! body: Hello world! category: about
Note: For associations to reference one another by name, you cannot specify
the id:
attribute on the fixtures. Rails will auto assign a
primary key to be consistent between runs. If you manually specify an
id:
attribute, this behavior will not work. For more
information on this association behavior please read the fixture
api documentation.
ERB'in It Up¶ ↑
ERB allows you to embed Ruby code within templates. The YAML fixture format is pre-processed with ERB when Rails loads fixtures. This allows you to use Ruby to help you generate some sample data. For example, the following code generates a thousand users:
<% 1000.times do |n| %> user_<%= n %>: username: <%= "user#{n}" %> email: <%=<EMAIL_ADDRESS>%> <% end %>
Fixtures in Action¶ ↑
Rails by default automatically loads all fixtures from the
test/fixtures
folder for your models and controllers test.
Loading involves three steps:
-
Remove any existing data from the table corresponding to the fixture
-
Load the fixture data into the table
-
Dump the fixture data into a variable in case you want to access it directly
Fixtures are Active Record objects¶ ↑
Fixtures are instances of Active Record. As mentioned in point #3 above, you can access the object directly because it is automatically setup as a local variable of the test case. For example:
# this will return the User object for the fixture named david users(:david) # this will return the property for david called id users(:david).id # one can also access methods available on the User class email(david.girlfriend.email, david.location_tonight)
Unit Testing your Models¶ ↑
In Rails, models tests are what you write to test your models.
For this guide we will be using Rails scaffolding. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practices. We will be using examples from this generated code and will be supplementing it with additional examples where necessary.
NOTE: For more information on Rails scaffolding, refer to Getting Started with Rails
When you use rails generate scaffold
, for a resource among
other things it creates a test stub in the test/models
folder:
$ bin/rails generate scaffold article title:string body:text ... create app/models/article.rb create test/models/article_test.rb create test/fixtures/articles.yml ...
The default test stub in test/models/article_test.rb
looks
like this:
require 'test_helper' class ArticleTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
A line by line examination of this file will help get you oriented to Rails testing code and terminology.
require 'test_helper'
As you know by now, test_helper.rb
specifies the default
configuration to run our tests. This is included with all the tests, so any
methods added to this file are available to all your tests.
class ArticleTest < ActiveSupport::TestCase
The ArticleTest
class defines a test case because it
inherits from ActiveSupport::TestCase
.
ArticleTest
thus has all the methods available from
ActiveSupport::TestCase
. You'll see those methods a little
later in this guide.
Any method defined within a class inherited from
Minitest::Test
(which is the superclass of
ActiveSupport::TestCase
) that begins with test_
(case sensitive) is simply called a test. So, test_password
and test_valid_password
are legal test names and are run
automatically when the test case is run.
Rails adds a test
method that takes a test name and a block.
It generates a normal Minitest::Unit
test with method names
prefixed with test_
. So,
test "the truth" do assert true end
acts as if you had written
def test_the_truth assert true end
only the test
macro allows a more readable test name. You can
still use regular method definitions though.
NOTE: The method name is generated by replacing spaces with underscores.
The result does not need to be a valid Ruby identifier though, the name may
contain punctuation characters etc. That's because in Ruby technically
any string may be a method name. Odd ones need define_method
and send
calls, but formally there's no restriction.
assert true
This line of code is called an assertion. An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check:
-
does this value = that value?
-
is this object nil?
-
does this line of code throw an exception?
-
is the user's password greater than 5 characters?
Every test contains one or more assertions. Only when all the assertions are successful will the test pass.
Maintaining the test database schema¶ ↑
In order to run your tests, your test database will need to have the
current structure. The test helper checks whether your test database has
any pending migrations. If so, it will try to load your
db/schema.rb
or db/structure.sql
into the test
database. If migrations are still pending, an error will be raised. Usually
this indicates that your schema is not fully migrated. Running the
migrations against the development database (bin/rake
db:migrate
) will bring the schema up to date.
NOTE: If existing migrations required modifications, the test database
needs to be rebuilt. This can be done by executing bin/rake
db:test:prepare
.
Running Tests¶ ↑
Running a test is as simple as invoking the file containing the test cases
through rake test
command.
$ bin/rake test test/models/article_test.rb . Finished tests in 0.009262s, 107.9680 tests/s, 107.9680 assertions/s. 1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
You can also run a particular test method from the test case by running the
test and providing the test method name
.
$ bin/rake test test/models/article_test.rb test_the_truth . Finished tests in 0.009064s, 110.3266 tests/s, 110.3266 assertions/s. 1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
This will run all test methods from the test case. Note that
test_helper.rb
is in the test
directory, hence
this directory needs to be added to the load path using the -I
switch.
The .
(dot) above indicates a passing test. When a test fails
you see an F
; when a test throws an error you see an
E
in its place. The last line of the output is the summary.
To see how a test failure is reported, you can add a failing test to the
article_test.rb
test case.
test "should not save article without title" do article = Article.new assert_not article.save end
Let us run this newly added test.
$ bin/rake test test/models/article_test.rb test_should_not_save_article_without_title F Finished tests in 0.044632s, 22.4054 tests/s, 22.4054 assertions/s. 1) Failure: test_should_not_save_article_without_title(ArticleTest) [test/models/article_test.rb:6]: Failed assertion, no message given. 1 tests, 1 assertions, 1 failures, 0 errors, 0 skips
In the output, F
denotes a failure. You can see the
corresponding trace shown under 1)
along with the name of the
failing test. The next few lines contain the stack trace followed by a
message which mentions the actual value and the expected value by the
assertion. The default assertion messages provide just enough information
to help pinpoint the error. To make the assertion failure message more
readable, every assertion provides an optional message parameter, as shown
here:
test "should not save article without title" do article = Article.new assert_not article.save, "Saved the article without a title" end
Running this test shows the friendlier assertion message:
1) Failure: test_should_not_save_article_without_title(ArticleTest) [test/models/article_test.rb:6]: Saved the article without a title
Now to get this test to pass we can add a model level validation for the title field.
class Article < ActiveRecord::Base validates :title, presence: true end
Now the test should pass. Let us verify by running the test again:
$ bin/rake test test/models/article_test.rb test_should_not_save_article_without_title . Finished tests in 0.047721s, 20.9551 tests/s, 20.9551 assertions/s. 1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
Now, if you noticed, we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as Test-Driven Development (TDD).
TIP: Many Rails developers practice Test-Driven Development (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with 15 TDD steps to create a Rails application.
To see how an error gets reported, here's a test containing an error:
test "should report error" do # some_undefined_variable is not defined elsewhere in the test case some_undefined_variable assert true end
Now you can see even more output in the console from running the tests:
$ bin/rake test test/models/article_test.rb test_should_report_error E Finished tests in 0.030974s, 32.2851 tests/s, 0.0000 assertions/s. 1) Error: test_should_report_error(ArticleTest): NameError: undefined local variable or method `some_undefined_variable' for #<ArticleTest:0x007fe32e24afe0> test/models/article_test.rb:10:in `block in <class:ArticleTest>' 1 tests, 0 assertions, 0 failures, 1 errors, 0 skips
Notice the 'E' in the output. It denotes a test with error.
NOTE: The execution of each test method stops as soon as any error or an assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
When a test fails you are presented with the corresponding backtrace. By
default Rails filters that backtrace and will only print lines relevant to
your application. This eliminates the framework noise and helps to focus on
your code. However there are situations when you want to see the full
backtrace. simply set the BACKTRACE
environment variable to
enable this behavior:
$ BACKTRACE=1 bin/rake test test/models/article_test.rb
What to Include in Your Unit Tests¶ ↑
Ideally, you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.
Available Assertions¶ ↑
By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.
There are a bunch of different types of assertions you can use. Here's
an extract of the assertions you can use with Minitest, the default
testing library used by Rails. The [msg]
parameter is an
optional string message you can specify to make your test failure messages
clearer. It's not required.
| Assertion | Purpose | | —————————————————————- | ——- | | assert(
test, [msg] )
| Ensures that test
is true.| |
assert_not( test, [msg] )
| Ensures that test
is
false.| | assert_equal( expected, actual, [msg] )
| Ensures
that expected == actual
is true.| | assert_not_equal(
expected, actual, [msg] )
| Ensures that expected !=
actual
is true.| | assert_same( expected, actual, [msg]
)
| Ensures that expected.equal?(actual)
is true.| |
assert_not_same( expected, actual, [msg] )
| Ensures that
expected.equal?(actual)
is false.| | assert_nil( obj,
[msg] )
| Ensures that obj.nil?
is true.| |
assert_not_nil( obj, [msg] )
| Ensures that
obj.nil?
is false.| | assert_empty( obj, [msg] )
| Ensures that obj
is empty?
.| |
assert_not_empty( obj, [msg] )
| Ensures that obj
is not empty?
.| | assert_match( regexp, string, [msg]
)
| Ensures that a string matches the regular expression.| |
assert_no_match( regexp, string, [msg] )
| Ensures that a
string doesn't match the regular expression.| | assert_includes(
collection, obj, [msg] )
| Ensures that obj
is in
collection
.| | assert_not_includes( collection, obj,
[msg] )
| Ensures that obj
is not in
collection
.| | assert_in_delta( expecting, actual,
[delta], [msg] )
| Ensures that the numbers expected
and actual
are within delta
of each other.| |
assert_not_in_delta( expecting, actual, [delta], [msg] )
|
Ensures that the numbers expected
and actual
are
not within delta
of each other.| | assert_throws(
symbol, [msg] ) { block }
| Ensures that the given block throws the
symbol.| | assert_raises( exception1, exception2, ... ) { block
}
| Ensures that the given block raises one of the given
exceptions.| | assert_nothing_raised( exception1, exception2, ... ) {
block }
| Ensures that the given block doesn't raise one of the
given exceptions.| | assert_instance_of( class, obj, [msg] )
|
Ensures that obj
is an instance of class
.| |
assert_not_instance_of( class, obj, [msg] )
| Ensures that
obj
is not an instance of class
.| |
assert_kind_of( class, obj, [msg] )
| Ensures that
obj
is or descends from class
.| |
assert_not_kind_of( class, obj, [msg] )
| Ensures that
obj
is not an instance of class
and is not
descending from it.| | assert_respond_to( obj, symbol, [msg] )
| Ensures that obj
responds to symbol
.| |
assert_not_respond_to( obj, symbol, [msg] )
| Ensures that
obj
does not respond to symbol
.| |
assert_operator( obj1, operator, [obj2], [msg] )
| Ensures
that obj1.operator(obj2)
is true.| |
assert_not_operator( obj1, operator, [obj2], [msg] )
| Ensures
that obj1.operator(obj2)
is false.| | assert_predicate (
obj, predicate, [msg] )
| Ensures that obj.predicate
is
true, e.g. assert_predicate str, :empty?
| |
assert_not_predicate ( obj, predicate, [msg] )
| Ensures that
obj.predicate
is false, e.g. assert_not_predicate str,
:empty?
| | assert_send( array, [msg] )
| Ensures that
executing the method listed in array[1]
on the object in
array[0]
with the parameters of array[2 and up]
is true. This one is weird eh?| | flunk( [msg] )
| Ensures
failure. This is useful to explicitly mark a test that isn't finished
yet.|
The above are subset of assertions that minitest supports. For an exhaustive & more up-to-date list, please check Minitest API documentation, specifically Minitest::Assertions
Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It includes some specialized assertions to make your life easier.
NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.
Rails Specific Assertions¶ ↑
Rails adds some custom assertions of its own to the minitest
framework:
| Assertion | Purpose | | ——————————————————————————— | ——- | |
assert_difference(expressions, difference = 1, message = nil) {...} |
Test numeric difference between the return value of an expression as a
result of what is evaluated in the yielded block.| |
assert_no_difference(expressions, message = nil, &block) | Asserts that
the numeric result of evaluating an expression is not changed before and
after invoking the passed in block.| | assert_recognizes(expected_options,
path, extras={}, message=nil) | Asserts that the routing of the given path
was handled correctly and that the parsed options (given in the
expected_options hash) match path. Basically, it asserts that Rails
recognizes the route given by expected_options.| |
assert_generates(expected_path, options, defaults={}, extras = {},
message=nil) | Asserts that the provided options can be used to generate
the provided path. This is the inverse of assert_recognizes. The extras
parameter is used to tell the request the names and values of additional
request parameters that would be in a query string. The message parameter
allows you to specify a custom error message for assertion failures.| |
assert_response(type, message = nil) | Asserts that the response comes with
a specific status code. You can specify :success to indicate 200-299,
:redirect to indicate 300-399, :missing to indicate 404, or :error to match
the 500-599 range. You can also pass an explicit status number or its
symbolic equivalent. For more information, see {full list of status
codes}[http://rubydoc.info/github/rack/rack/master/Rack/Utils#HTTP_STATUS_CODES-constant]
and how their mapping
works.| | assert_redirected_to(options = {}, message=nil)
|
Assert that the redirection options passed in match those of the redirect
called in the latest action. This match can be partial, such that
assert_redirected_to(controller: "weblog")
will also
match the redirection of redirect_to(controller: "weblog",
action: "show")
and so on. You can also pass named routes
such as assert_redirected_to root_path
and Active Record
objects such as assert_redirected_to @article
.| |
assert_template(expected = nil, message=nil)
| Asserts that
the request was rendered with the appropriate template file.|
You'll see the usage of some of these assertions in the next chapter.
Functional Tests for Your Controllers¶ ↑
In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
What to Include in your Functional Tests¶ ↑
You should test for things such as:
-
was the web request successful?
-
was the user redirected to the right page?
-
was the user successfully authenticated?
-
was the correct object stored in the response template?
-
was the appropriate message displayed to the user in the view?
Now that we have used Rails scaffold generator for our Article
resource, it has already created the controller code and tests. You can
take look at the file articles_controller_test.rb
in the
test/controllers
directory.
Let me take you through one such test, test_should_get_index
from the file articles_controller_test.rb
.
class ArticlesControllerTest < ActionController::TestCase test "should get index" do get :index assert_response :success assert_not_nil assigns(:articles) end end
In the test_should_get_index
test, Rails simulates a request
on the action called index
, making sure the request was
successful and also ensuring that it assigns a valid articles
instance variable.
The get
method kicks off the web request and populates the
results into the response. It accepts 4 arguments:
-
The action of the controller you are requesting. This can be in the form of a string or a symbol.
-
An optional hash of request parameters to pass into the action (eg. query string parameters or article variables).
-
An optional hash of session variables to pass along with the request.
-
An optional hash of flash values.
Example: Calling the :show
action, passing an id
of 12 as the params
and setting a user_id
of 5 in
the session:
get(:show, {'id' => "12"}, {'user_id' => 5})
Another example: Calling the :view
action, passing an
id
of 12 as the params
, this time with no
session, but with a flash message.
get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
NOTE: If you try running test_should_create_article
test from
articles_controller_test.rb
it will fail on account of the
newly added model level validation and rightly so.
Let us modify test_should_create_article
test in
articles_controller_test.rb
so that all our test pass:
test "should create article" do assert_difference('Article.count') do post :create, article: {title: 'Some title'} end assert_redirected_to article_path(assigns(:article)) end
Now you can try running all the tests and they should pass.
Available Request Types for Functional Tests¶ ↑
If you're familiar with the HTTP protocol, you'll know that
get
is a type of request. There are 6 request types supported
in Rails functional tests:
-
get
-
post
-
patch
-
put
-
head
-
delete
All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others.
NOTE: Functional tests do not verify whether the specified request type should be accepted by the action. Request types in this context exist to make your tests more descriptive.
The Four Hashes of the Apocalypse¶ ↑
After a request has been made using one of the 6 methods (get
,
post
, etc.) and processed, you will have 4 Hash objects ready
for use:
-
assigns
- Any objects that are stored as instance variables in actions for use in views. -
cookies
- Any cookies that are set. -
flash
- Any objects living in the flash. -
session
- Any object living in session variables.
As is the case with normal Hash objects, you can access the values by
referencing the keys by string. You can also reference them by symbol name,
except for assigns
. For example:
flash["gordon"] flash[:gordon] session["shmession"] session[:shmession] cookies["are_good_for_u"] cookies[:are_good_for_u] # Because you can't use assigns[:something] for historical reasons: assigns["something"] assigns(:something)
Instance Variables Available¶ ↑
You also have access to three instance variables in your functional tests:
-
@controller
- The controller processing the request -
@request
- The request -
@response
- The response
Setting Headers and CGI variables¶ ↑
HTTP headers
and CGI
variables can be set directly on the @request
instance
variable:
# setting a HTTP Header @request.headers["Accept"] = "text/plain, text/html" get :index # simulate the request with custom header # setting a CGI variable @request.headers["HTTP_REFERER"] = "http://example.com/home" post :create # simulate the request with custom env variable
Testing Templates and Layouts¶ ↑
If you want to make sure that the response rendered the correct template
and layout, you can use the assert_template
method:
test "index should render correct template and layout" do get :index assert_template :index assert_template layout: "layouts/application" end
Note that you cannot test for template and layout at the same time, with
one call to assert_template
method. Also, for the
layout
test, you can give a regular expression instead of a
string, but using the string, makes things clearer. On the other hand, you
have to include the “layouts” directory name even if you save your layout
file in this standard layout directory. Hence,
assert_template layout: "application"
will not work.
If your view renders any partial, when asserting for the layout, you have to assert for the partial at the same time. Otherwise, assertion will fail.
Hence:
test "new should render correct layout" do get :new assert_template layout: "layouts/application", partial: "_form" end
is the correct way to assert for the layout when the view renders a partial
with name _form
. Omitting the :partial
key in
your assert_template
call will complain.
A Fuller Functional Test Example¶ ↑
Here's another example that uses flash
,
assert_redirected_to
, and assert_difference
:
test "should create article" do assert_difference('Article.count') do post :create, article: {title: 'Hi', body: 'This is my first article.'} end assert_redirected_to article_path(assigns(:article)) assert_equal 'Article was successfully created.', flash[:notice] end
Testing Views¶ ↑
Testing the response to your request by asserting the presence of key HTML
elements and their content is a useful way to test the views of your
application. The assert_select
assertion allows you to do this
by using a simple yet powerful syntax.
NOTE: You may find references to assert_tag
in other
documentation. This has been removed in 4.2. Use assert_select
instead.
There are two forms of assert_select
:
assert_select(selector, [equality], [message])
ensures that
the equality condition is met on the selected elements through the
selector. The selector may be a CSS selector expression (String) or an
expression with substitution values.
assert_select(element, selector, [equality], [message])
ensures that the equality condition is met on all the selected elements
through the selector starting from the element (instance of
Nokogiri::XML::Node
or Nokogiri::XML::NodeSet
)
and its descendants.
For example, you could verify the contents on the title element in your response with:
assert_select 'title', "Welcome to Rails Testing Guide"
You can also use nested assert_select
blocks. In this case the
inner assert_select
runs the assertion on the complete
collection of elements selected by the outer assert_select
block:
assert_select 'ul.navigation' do assert_select 'li.menu_item' end
Alternatively the collection of elements selected by the outer
assert_select
may be iterated through so that
assert_select
may be called separately for each element.
Suppose for example that the response contains two ordered lists, each with
four list elements then the following tests will both pass.
assert_select "ol" do |elements| elements.each do |element| assert_select element, "li", 4 end end assert_select "ol" do assert_select "li", 8 end
The assert_select
assertion is quite powerful. For more
advanced usage, refer to its documentation.
Additional View-Based Assertions¶ ↑
There are more assertions that are primarily used in testing views:
| Assertion | Purpose | | ——————————————————— | ——- | |
assert_select_email
| Allows you to make assertions on the
body of an e-mail. | | assert_select_encoded
| Allows you to
make assertions on encoded HTML. It does this by un-encoding the contents
of each element and then calling the block with all the un-encoded
elements.| | css_select(selector)
or css_select(element,
selector)
| Returns an array of all the elements selected by the
selector. In the second variant it first matches the base
element and tries to match the selector expression on any
of its children. If there are no matches both variants return an empty
array.|
Here's an example of using assert_select_email
:
assert_select_email do assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.' end
Integration Testing¶ ↑
Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.
Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you.
$ bin/rails generate integration_test user_flows exists test/integration/ create test/integration/user_flows_test.rb
Here's what a freshly-generated integration test looks like:
require 'test_helper' class UserFlowsTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end end
Integration tests inherit from
ActionDispatch::IntegrationTest
. This makes available some
additional helpers to use in your integration tests. Also you need to
explicitly include the fixtures to be made available to the test.
Helpers Available for Integration Tests¶ ↑
In addition to the standard testing helpers, there are some additional helpers available to integration tests:
| Helper | Purpose | | —————————————————————— | ——- | | https?
| Returns true
if the session is mimicking a secure HTTPS
request.| | https!
| Allows you to mimic a secure HTTPS
request.| | host!
| Allows you to set the host name to use in
the next request.| | redirect?
| Returns true
if
the last request was a redirect.| | follow_redirect!
| Follows
a single redirect response.| | request_via_redirect(http_method,
path, [parameters], [headers])
| Allows you to make an HTTP request
and follow any subsequent redirects.| | post_via_redirect(path,
[parameters], [headers])
| Allows you to make an HTTP POST request
and follow any subsequent redirects.| | get_via_redirect(path,
[parameters], [headers])
| Allows you to make an HTTP GET request
and follow any subsequent redirects.| | patch_via_redirect(path,
[parameters], [headers])
| Allows you to make an HTTP PATCH request
and follow any subsequent redirects.| | put_via_redirect(path,
[parameters], [headers])
| Allows you to make an HTTP PUT request
and follow any subsequent redirects.| | delete_via_redirect(path,
[parameters], [headers])
| Allows you to make an HTTP DELETE request
and follow any subsequent redirects.| | open_session
| Opens a
new session instance.|
Integration Testing Examples¶ ↑
A simple integration test that exercises multiple controllers:
require 'test_helper' class UserFlowsTest < ActionDispatch::IntegrationTest test "login and browse site" do # login via https https! get "/login" assert_response :success post_via_redirect "/login", username: users(:david).username, password: users(:david).password assert_equal '/welcome', path assert_equal 'Welcome david!', flash[:notice] https!(false) get "/articles/all" assert_response :success assert assigns(:articles) end end
As you can see the integration test involves multiple controllers and exercises the entire stack from database to dispatcher. In addition you can have multiple session instances open simultaneously in a test and extend those instances with assertion methods to create a very powerful testing DSL (domain-specific language) just for your application.
Here's an example of multiple sessions and custom DSL in an integration test
require 'test_helper' class UserFlowsTest < ActionDispatch::IntegrationTest test "login and browse site" do # User david logs in david = login(:david) # User guest logs in guest = login(:guest) # Both are now available in different sessions assert_equal 'Welcome david!', david.flash[:notice] assert_equal 'Welcome guest!', guest.flash[:notice] # User david can browse site david.browses_site # User guest can browse site as well guest.browses_site # Continue with other assertions end private module CustomDsl def browses_site get "/products/all" assert_response :success assert assigns(:products) end end def login(user) open_session do |sess| sess.extend(CustomDsl) u = users(user) sess.https! sess.post "/login", username: u.username, password: u.password assert_equal '/welcome', sess.path sess.https!(false) end end end
Rake Tasks for Running your Tests¶ ↑
Rails comes with a number of built-in rake tasks to help with testing. The table below lists the commands included in the default Rakefile when a Rails project is created.
| Tasks | Description | | ———————– | ———– | | rake test
| Runs
all tests in the test
folder. You can also simply run
rake
as Rails will run all the tests by default | | rake
test:controllers
| Runs all the controller tests from
test/controllers
| | rake test:functionals
| Runs
all the functional tests from test/controllers
,
test/mailers
, and test/functional
| | rake
test:helpers
| Runs all the helper tests from
test/helpers
| | rake test:integration
| Runs all
the integration tests from test/integration
| | rake
test:jobs
| Runs all the job tests from test/jobs
| |
rake test:mailers
| Runs all the mailer tests from
test/mailers
| | rake test:models
| Runs all the
model tests from test/models
| | rake test:units
| Runs all the unit tests from test/models
,
test/helpers
, and test/unit
| | rake
test:db
| Runs all tests in the test
folder and resets
the db |
A Brief Note About Minitest¶ ↑
Ruby ships with a vast Standard Library for all common use-cases including
testing. Since version 1.9, Ruby provides Minitest
, a
framework for testing. All the basic assertions such as
assert_equal
discussed above are actually defined in
Minitest::Assertions
. The classes
ActiveSupport::TestCase
,
ActionController::TestCase
,
ActionMailer::TestCase
, ActionView::TestCase
and
ActionDispatch::IntegrationTest
- which we have been
inheriting in our test classes - include Minitest::Assertions
,
allowing us to use all of the basic assertions in our tests.
NOTE: For more information on Minitest
, refer to Minitest
Setup and Teardown¶ ↑
If you would like to run a block of code before the start of each test and
another block of code after the end of each test you have two special
callbacks for your rescue. Let's take note of this by looking at an
example for our functional test in Articles
controller:
require 'test_helper' class ArticlesControllerTest < ActionController::TestCase # called before every single test def setup @article = articles(:one) end # called after every single test def teardown # as we are re-initializing @article before every test # setting it to nil here is not essential but I hope # you understand how you can use the teardown method @article = nil end test "should show article" do get :show, id: @article.id assert_response :success end test "should destroy article" do assert_difference('Article.count', -1) do delete :destroy, id: @article.id end assert_redirected_to articles_path end end
Above, the setup
method is called before each test and so
@article
is available for each of the tests. Rails implements
setup
and teardown
as
ActiveSupport::Callbacks
. Which essentially means you need not
only use setup
and teardown
as methods in your
tests. You could specify them by using:
-
a block
-
a method (like in the earlier example)
-
a method name as a symbol
-
a lambda
Let's see the earlier example by specifying setup
callback
by specifying a method name as a symbol:
require 'test_helper' class ArticlesControllerTest < ActionController::TestCase # called before every single test setup :initialize_article # called after every single test def teardown @article = nil end test "should show article" do get :show, id: @article.id assert_response :success end test "should update article" do patch :update, id: @article.id, article: {} assert_redirected_to article_path(assigns(:article)) end test "should destroy article" do assert_difference('Article.count', -1) do delete :destroy, id: @article.id end assert_redirected_to articles_path end private def initialize_article @article = articles(:one) end end
Testing Routes¶ ↑
Like everything else in your Rails application, it is recommended that you
test your routes. Below are example tests for the routes of default
show
and create
action of Articles
controller above and it should look like:
class ArticleRoutesTest < ActionController::TestCase test "should route to article" do assert_routing '/articles/1', { controller: "articles", action: "show", id: "1" } end test "should route to create article" do assert_routing({ method: 'post', path: '/articles' }, { controller: "articles", action: "create" }) end end
Testing Your Mailers¶ ↑
Testing mailer classes requires some specific tools to do a thorough job.
Keeping the Postman in Check¶ ↑
Your mailer classes - like every other part of your Rails application - should be tested to ensure that it is working as expected.
The goals of testing your mailer classes are to ensure that:
-
emails are being processed (created and sent)
-
the email content is correct (subject, sender, body, etc)
-
the right emails are being sent at the right times
From All Sides¶ ↑
There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a known value (a fixture.) In the functional tests you don't so much test the minute details produced by the mailer; instead, we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.
Unit Testing¶ ↑
In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced.
Revenge of the Fixtures¶ ↑
For the purposes of unit testing a mailer, fixtures are used to provide an
example of how the output should look. Because these are example
emails, and not Active Record data like the other fixtures, they are kept
in their own subdirectory apart from the other fixtures. The name of the
directory within test/fixtures
directly corresponds to the
name of the mailer. So, for a mailer named UserMailer
, the
fixtures should reside in test/fixtures/user_mailer
directory.
When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.
The Basic Test Case¶ ↑
Here's a unit test to test a mailer named UserMailer
whose
action invite
is used to send an invitation to a friend. It is
an adapted version of the base test created by the generator for an
invite
action.
require 'test_helper' class UserMailerTest < ActionMailer::TestCase test "invite" do # Send the email, then test that it got queued email =<EMAIL_ADDRESS><EMAIL_ADDRESS>Time.now).deliver_now assert_not ActionMailer::Base.deliveries.empty? # Test the body of the sent email contains what we expect it to assert_equal<EMAIL_ADDRESS>email.from assert_equal<EMAIL_ADDRESS>email.to assert_equal 'You have been invited by<EMAIL_ADDRESS>email.subject assert_equal read_fixture('invite').join, email.body.to_s end end
In the test we send the email and store the returned object in the
email
variable. We then ensure that it was sent (the first
assert), then, in the second batch of assertions, we ensure that the email
does indeed contain what we expect. The helper read_fixture
is
used to read in the content from this file.
Here's the content of the invite
fixture:
Hi<EMAIL_ADDRESS>You have been invited. Cheers!
This is the right time to understand a little more about writing tests for
your mailers. The line ActionMailer::Base.delivery_method =
:test
in config/environments/test.rb
sets the delivery
method to test mode so that email will not actually be delivered (useful to
avoid spamming your users while testing) but instead it will be appended to
an array (ActionMailer::Base.deliveries
).
NOTE: The ActionMailer::Base.deliveries
array is only reset
automatically in ActionMailer::TestCase
tests. If you want to
have a clean slate outside Action Mailer tests, you can reset it manually
with: ActionMailer::Base.deliveries.clear
Functional Testing¶ ↑
Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job. You are probably more interested in whether your own business logic is sending emails when you expect them to go out. For example, you can check that the invite friend operation is sending an email appropriately:
require 'test_helper' class UserControllerTest < ActionController::TestCase test "invite friend" do assert_difference 'ActionMailer::Base.deliveries.size', +1 do post :invite_friend, email<EMAIL_ADDRESS>end invite_email = ActionMailer::Base.deliveries.last assert_equal "You have been invited by<EMAIL_ADDRESS>invite_email.subject assert_equal<EMAIL_ADDRESS>invite_email.to[0] assert_match(/Hi<EMAIL_ADDRESS>invite_email.body.to_s) end end
Testing helpers¶ ↑
In order to test helpers, all you need to do is check that the output of
the helper method matches what you'd expect. Tests related to the
helpers are located under the test/helpers
directory.
A helper test looks like so:
require 'test_helper' class UserHelperTest < ActionView::TestCase end
A helper is just a simple module where you can define methods which are available into your views. To test the output of the helper's methods, you just have to use a mixin like this:
class UserHelperTest < ActionView::TestCase include UserHelper test "should return the user name" do # ... end end
Moreover, since the test class extends from
ActionView::TestCase
, you have access to Rails' helper
methods such as link_to
or pluralize
.
Testing Jobs¶ ↑
Since your custom jobs can be queued at different levels inside your application, you'll need to test both jobs themselves (their behavior when they get enqueued) and that other entities correctly enqueue them.
A Basic Test Case¶ ↑
By default, when you generate a job, an associated test will be generated
as well under the test/jobs
directory. Here's an example
test with a billing job:
require 'test_helper' class BillingJobTest < ActiveJob::TestCase test 'that account is charged' do BillingJob.perform_now(account, product) assert account.reload.charged_for?(product) end end
This test is pretty simple and only asserts that the job get the work done as expected.
By default, ActiveJob::TestCase
will set the queue adapter to
:test
so that your jobs are performed inline. It will also
ensure that all previously performed and enqueued jobs are cleared before
any test run so you can safely assume that no jobs have already been
executed in the scope of each test.
Custom Assertions And Testing Jobs Inside Other Components¶ ↑
Active Job ships with a bunch of custom assertions that can be used to lessen the verbosity of tests:
| Assertion | Purpose | | ————————————– | ——- | |
assert_enqueued_jobs(number)
| Asserts that the number of
enqueued jobs matches the given number. | |
assert_performed_jobs(number)
| Asserts that the number of
performed jobs matches the given number. | | assert_no_enqueued_jobs
{ ... }
| Asserts that no jobs have been enqueued. | |
assert_no_performed_jobs { ... }
| Asserts that no jobs have
been performed. | | assert_enqueued_with([args]) { ... }
|
Asserts that the job passed in the block has been enqueued with the given
arguments. | | assert_performed_with([args]) { ... }
| Asserts
that the job passed in the block has been performed with the given
arguments. |
It's a good practice to ensure that your jobs correctly get enqueued or performed wherever you invoke them (e.g. inside your controllers). This is precisely where the custom assertions provided by Active Job are pretty useful. For instance, within a model:
require 'test_helper' class ProductTest < ActiveJob::TestCase test 'billing job scheduling' do assert_enqueued_with(job: BillingJob) do product.charge(account) end end end
Other Testing Approaches¶ ↑
The built-in minitest
based testing is not the only way to
test Rails applications. Rails developers have come up with a wide variety
of other approaches and aids for testing, including:
-
NullDB, a way to speed up testing by avoiding database use.
-
Factory Girl, a replacement for fixtures.
-
Fixture Builder, a tool that compiles Ruby factories into fixtures before a test run.
-
MiniTest::Spec Rails, use the MiniTest::Spec DSL within your rails tests.
-
Shoulda, an extension to
test/unit
with additional helpers, macros, and assertions. -
RSpec, a behavior-driven development framework
-
Capybara, Acceptance test framework for web applications


Your PC hasn't run into a problem (yet) and probably doesn't need to restart.
We are constantly collecting info for our marketing department.
Please provide your stop code as it will help you track the unstability of your system.
If you would like to see all stop codes your system has produces so far, please
click here


Click on part of the URL to learn more about it.
The anchor text is the clickable text of a link. The anchor text of a link embedded within an image is normally defined by the hidden "AltText" tag inserted into the web page.
A backlink is an incoming link from another site. For example, if site A had a link to site B on one of its web pages, then site B has a backlink to site A.
A root domain is synonymous with domain, and includes the domain name and top-level domain.
http://www.example.com/blog
A domain refers to another domain if it has at least one link to it on any of its web pages.
Trust Flow is a Majestic trademarked term that represents the quality of a site. Sites that are linked with a site with high Trust Flow will themselves have their trust flow increased, and the opposite if they are linked with a site with low trust flow.
Trust flow was originally allocated based on a manual review of the web's highest quality sites.
Citation Flow is another Majestic trademarked term that represents the "power" that the link or site carries, based on the number of backlinks it has. A high Citation Flow can indicate that a site is rich in web 'spam' or that it is just very popular.
The Majestic Flow Metrics (Trust Flow and Citation Flow) go hand in hand when determining a site's quality.
The Historic Index is the largest index of backlink history on the web and spans back more than 5 years. As building it takes days of processing power, the Fresh Index was introduced as an up-to-date database that contains crawled data from the past 90 days and is updated throughout the day.


Contact information
Telephone
Open Saturday to Thursday, from 8am to 6pm our technical service ( fixed, internet and mobile) are all day at your disposal, including public holidays.
- For mobile / 1777 or<PHONE_NUMBER>
- For fixed & internet / 1214 or 06 460 8888
- For enterprise / 1215 or 06 5630090 06 5512800


cecropiasolutions.com
The Hall
start experience
VR
: Hand controllers and teleport with trigger.
Desktop
: Keyboard (WASD/arrows) and mouse.
Mobile
: Gaze cursor and teleportation.


{% include "templates/generators/item/item_image.html" %}
{% include "templates/generators/item/item_details.html" %}
{% include "templates/generators/item/item_specifications.html" %}
{{ doc.website_content or '' }}
{% extends "templates/web.html" %} {% block title %} {{ website_title_qr or title }} {% endblock %} {% block breadcrumbs %} {% include "templates/includes/breadcrumbs.html" %} {% endblock %} {% block page_content %}


You don't have any conversion yet. Upload a Revit model to get started.
| Name | {{row.name}} | Status | {{row.status}} | Date | {{ row.date | date:"MMM d, y, h:mm a" }} | Report | summarize | Download | Download File |
|---|---|---|---|
| No data matching the filter "{{input.value}}" |
All converted files will stay available here for 30 days.


One’s condition on marijuana is always existential. One can feel the importance of each moment and how it is changing one. One feels one’s being, one becomes aware of the enormous apparatus of nothingness—the hum of a hi-fi set, the emptiness of a pointless interruption, one becomes aware of the war between each of us, how the nothingness in each of us seeks to attack the being of others, how our being in turn is attacked by the nothingness in others.
- - Norman Mailer - in Writers at Work
I've had an *overwhelming* reaction to marijuana. I consider myself a fairly heavy user of the herb. But for some reason instead of being high and in the groove, I was having a very bad trip and nausea, no psychedelics involved.
I was at 2 aquaintances' apt with my best friend and his old high school friend. We had smoked some hash I brought from Am'dam, a couple fatties and christened a new glass bong. More than I usually smoke, but nothing I didn't think I could handle.
But then my high became adverse. My body was disassociating. Music was coming out of the ambient white noise. I asked my friends, 'do you hear that beautiful music?' Negative. I was alone. Then the waves of evil started lapping at my feet. The 2 aquaintances took on a new persona. I took on a strange delirium. I believed that the man was satan, and his female roomate was his succubi. Caught in this thought loop, my body would revolt each time I thought about the satan connection.
I snuck away to the bathroom because I felt I had to vomit. Dry heaves. I couldn't commit my body to release the evil. I kept thinking of what someone said to me about vomiting as a means of cleansing.  My friend came in to check on me, and we decided to leave. I made it home and was finally able to release and give in to the vomiting and all was better. Lesson learned, don't fight the urge to spew. Purged and cleansed, I lied on the floor in the darkness, finally able to enjoy the space in my mind. No more bad thoughts. I continued hearing music from white noise and tried my best to remember the melodies so that I could tune in later.
All in all, a new and exciting experience from pot. Never thought it would be possible. Why do I think it happened? I had a large amount of Indian food for lunch, and I think there was a synergy from the spices. Yea, it could be food poisoning, but my girlfriend wasn't sick at all. This experience reinforced my belief that MJ is definitely a visionary plant. I'll probably try to repeat the indian food + copious mj combo just to satisfy my curiosity. However, the taste of curried bile is a poignant reminder that lingers on my tongue.
Experience Reports are the writings and opinions of the individual authors who submit them.
Some of the activities described are dangerous and/or illegal and none are recommended by Erowid.


Layouts and Rendering in Rails¶ ↑
This guide covers the basic layout features of Action Controller and Action View.
After reading this guide, you will know:
-
How to use the various rendering methods built into Rails.
-
How to create layouts with multiple content sections.
-
How to use partials to DRY up your views.
-
How to use nested layouts (sub-templates).
Overview: How the Pieces Fit Together¶ ↑
This guide focuses on the interaction between Controller and View in the Model-View-Controller triangle. As you know, the Controller is responsible for orchestrating the whole process of handling a request in Rails, though it normally hands off any heavy code to the Model. But then, when it's time to send a response back to the user, the Controller hands things off to the View. It's that handoff that is the subject of this guide.
In broad strokes, this involves deciding what should be sent as the response and calling an appropriate method to create that response. If the response is a full-blown view, Rails also does some extra work to wrap the view in a layout and possibly to pull in partial views. You'll see all of those paths later in this guide.
Creating Responses¶ ↑
From the controller's point of view, there are three ways to create an HTTP response:
-
Call
render
to create a full response to send back to the browser -
Call
redirect_to
to send an HTTP redirect status code to the browser -
Call
head
to create a response consisting solely of HTTP headers to send back to the browser
Rendering by Default: Convention Over Configuration in Action¶ ↑
You've heard that Rails promotes “convention over configuration”.
Default rendering is an excellent example of this. By default, controllers
in Rails automatically render views with names that correspond to valid
routes. For example, if you have this code in your
BooksController
class:
class BooksController < ApplicationController end
And the following in your routes file:
resources :books
And you have a view file app/views/books/index.html.erb
:

Books are coming soon!

Rails will automatically render app/views/books/index.html.erb
when you navigate to /books
and you will see “Books are coming
soon!” on your screen.
However a coming soon screen is only minimally useful, so you will soon
create your Book
model and add the index action to
BooksController
:
class BooksController < ApplicationController def index @books = Book.all end end
Note that we don't have explicit render at the end of the index action
in accordance with “convention over configuration” principle. The rule is
that if you do not explicitly render something at the end of a controller
action, Rails will automatically look for the
action_name.html.erb
template in the controller's view
path and render it. So in this case, Rails will render the
app/views/books/index.html.erb
file.
If we want to display the properties of all the books in our view, we can do so with an ERB template like this:

Listing Books

 Title	 Summary
 <% @books.each do |book| %>
 <%= book.title %>	 <%= book.content %>	 <%= link_to "Show", book %>	 <%= link_to "Edit", edit_book_path(book) %>	 <%= link_to "Remove", book, method: :delete, data: { confirm: "Are you sure?" } %>
 <% end %>

 <%= link_to "New book", new_book_path %>
NOTE: The actual rendering is done by subclasses of
ActionView::TemplateHandlers
. This guide does not dig into
that process, but it's important to know that the file extension on
your view controls the choice of template handler. Beginning with Rails 2,
the standard extensions are .erb
for ERB (HTML with embedded
Ruby), and .builder
for Builder (XML generator).
Using render
¶ ↑
In most cases, the ActionController::Base#render
method does
the heavy lifting of rendering your application's content for use by a
browser. There are a variety of ways to customize the behavior of
render
. You can render the default view for a Rails template,
or a specific template, or a file, or inline code, or nothing at all. You
can render text, JSON, or XML. You can specify the content type or HTTP
status of the rendered response as well.
TIP: If you want to see the exact results of a call to render
without needing to inspect it in a browser, you can call
render_to_string
. This method takes exactly the same options
as render
, but it returns a string instead of sending a
response back to the browser.
Rendering Nothing¶ ↑
Perhaps the simplest thing you can do with render
is to render
nothing at all:
render nothing: true
If you look at the response for this using cURL, you will see the following:
$ curl -i <IP_ADDRESS>:3000/books HTTP/1.1 200 OK Connection: close Date: Sun, 24 Jan 2010 09:25:18 GMT Transfer-Encoding: chunked Content-Type: */*; charset=utf-8 X-Runtime: 0.014297 Set-Cookie: _blog_session=...snip...; path=/; HttpOnly Cache-Control: no-cache $
We see there is an empty response (no data after the
Cache-Control
line), but the request was successful because
Rails has set the response to 200 OK. You can set the :status
option on render to change this response. Rendering nothing can be useful
for Ajax requests where all you want to send back to the browser is an
acknowledgment that the request was completed.
TIP: You should probably be using the head
method, discussed
later in this guide, instead of render :nothing
. This provides
additional flexibility and makes it explicit that you're only
generating HTTP headers.
Rendering an Action's View¶ ↑
If you want to render the view that corresponds to a different template
within the same controller, you can use render
with the name
of the view:
def update @book = Book.find(params[:id]) if @book.update(book_params) redirect_to(@book) else render "edit" end end
If the call to update
fails, calling the update
action in this controller will render the edit.html.erb
template belonging to the same controller.
If you prefer, you can use a symbol instead of a string to specify the action to render:
def update @book = Book.find(params[:id]) if @book.update(book_params) redirect_to(@book) else render :edit end end
Rendering an Action's Template from Another Controller¶ ↑
What if you want to render a template from an entirely different controller
from the one that contains the action code? You can also do that with
render
, which accepts the full path (relative to
app/views
) of the template to render. For example, if
you're running code in an AdminProductsController
that
lives in app/controllers/admin
, you can render the results of
an action to a template in app/views/products
this way:
render "products/show"
Rails knows that this view belongs to a different controller because of the
embedded slash character in the string. If you want to be explicit, you can
use the :template
option (which was required on Rails 2.2 and
earlier):
render template: "products/show"
Rendering an Arbitrary File¶ ↑
The render
method can also use a view that's entirely
outside of your application (perhaps you're sharing views between two
Rails applications):
render "/u/apps/warehouse_app/current/app/views/products/show"
Rails determines that this is a file render because of the leading slash
character. To be explicit, you can use the :file
option (which
was required on Rails 2.2 and earlier):
render file: "/u/apps/warehouse_app/current/app/views/products/show"
The :file
option takes an absolute file-system path. Of
course, you need to have rights to the view that you're using to render
the content.
NOTE: By default, the file is rendered using the current layout.
TIP: If you're running Rails on Microsoft Windows, you should use the
:file
option to render a file, because Windows filenames do
not have the same format as Unix filenames.
Wrapping it up¶ ↑
The above three ways of rendering (rendering another template within the controller, rendering a template within another controller and rendering an arbitrary file on the file system) are actually variants of the same action.
In fact, in the BooksController class, inside of the update action where we
want to render the edit template if the book does not update successfully,
all of the following render calls would all render the
edit.html.erb
template in the views/books
directory:
render :edit render action: :edit render "edit" render "edit.html.erb" render action: "edit" render action: "edit.html.erb" render "books/edit" render "books/edit.html.erb" render template: "books/edit" render template: "books/edit.html.erb" render "/path/to/rails/app/views/books/edit" render "/path/to/rails/app/views/books/edit.html.erb" render file: "/path/to/rails/app/views/books/edit" render file: "/path/to/rails/app/views/books/edit.html.erb"
Which one you use is really a matter of style and convention, but the rule of thumb is to use the simplest one that makes sense for the code you are writing.
Using render
with :inline
¶ ↑
The render
method can do without a view completely, if
you're willing to use the :inline
option to supply ERB as
part of the method call. This is perfectly valid:
render inline: "<% products.each do |p| %>
<%= p.name %>
<% end %>"
WARNING: There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead.
By default, inline rendering uses ERB. You can force it to use Builder
instead with the :type
option:
render inline: "xml.p {'Horrid coding practice!'}", type: :builder
Rendering Text¶ ↑
You can send plain text - with no markup at all - back to the browser by
using the :plain
option to render
:
render plain: "OK"
TIP: Rendering pure text is most useful when you're responding to Ajax or web service requests that are expecting something other than proper HTML.
NOTE: By default, if you use the :plain
option, the text is
rendered without using the current layout. If you want Rails to put the
text into the current layout, you need to add the layout: true
option and use the .txt.erb
extension for the layout file.
Rendering HTML¶ ↑
You can send a HTML string back to the browser by using the
:html
option to render
:
render html: "Not Found".html_safe
TIP: This is useful when you're rendering a small snippet of HTML code. However, you might want to consider moving it to a template file if the markup is complex.
NOTE: This option will escape HTML entities if the string is not HTML safe.
Rendering JSON¶ ↑
JSON is a JavaScript data format used by many Ajax libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser:
render json: @product
TIP: You don't need to call to_json
on the object that you
want to render. If you use the :json
option,
render
will automatically call to_json
for you.
Rendering XML¶ ↑
Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:
render xml: @product
TIP: You don't need to call to_xml
on the object that you
want to render. If you use the :xml
option,
render
will automatically call to_xml
for you.
Rendering Vanilla JavaScript¶ ↑
Rails can render vanilla JavaScript:
render js: "alert('Hello Rails');"
This will send the supplied string to the browser with a MIME type of
text/javascript
.
Rendering raw body¶ ↑
You can send a raw content back to the browser, without setting any content
type, by using the :body
option to render
:
render body: "raw"
TIP: This option should be used only if you don't care about the
content type of the response. Using :plain
or
:html
might be more appropriate in most of the time.
NOTE: Unless overridden, your response returned from this render option
will be text/html
, as that is the default content type of
Action Dispatch response.
Options for render
¶ ↑
Calls to the render
method generally accept four options:
-
:content_type
-
:layout
-
:location
-
:status
The :content_type
Option¶ ↑
By default, Rails will serve the results of a rendering operation with the
MIME content-type of text/html
(or
application/json
if you use the :json
option, or
application/xml
for the :xml
option.). There are
times when you might like to change this, and you can do so by setting the
:content_type
option:
render file: filename, content_type: "application/rss"
The :layout
Option¶ ↑
With most of the options to render
, the rendered content is
displayed as part of the current layout. You'll learn more about
layouts and how to use them later in this guide.
You can use the :layout
option to tell Rails to use a specific
file as the layout for the current action:
render layout: "special_layout"
You can also tell Rails to render with no layout at all:
render layout: false
The :location
Option¶ ↑
You can use the :location
option to set the HTTP
Location
header:
render xml: photo, location: photo_url(photo)
The :status
Option¶ ↑
Rails will automatically generate a response with the correct HTTP status
code (in most cases, this is 200 OK
). You can use the
:status
option to change this:
render status: 500 render status: :forbidden
Rails understands both numeric status codes and the corresponding symbols shown below.
| Response Class | HTTP Status Code | Symbol | | ——————- | —————- | ——————————– | | Informational | 100 | :continue | | | 101 | :switching_protocols | | | 102 | :processing | | Success | 200 | :ok | | | 201 | :created | | | 202 | :accepted | | | 203 | :non_authoritative_information | | | 204 | :no_content | | | 205 | :reset_content | | | 206 | :partial_content | | | 207 | :multi_status | | | 208 | :already_reported | | | 226 | :im_used | | Redirection | 300 | :multiple_choices | | | 301 | :moved_permanently | | | 302 | :found | | | 303 | :see_other | | | 304 | :not_modified | | | 305 | :use_proxy | | | 306 | :reserved | | | 307 | :temporary_redirect | | | 308 | :permanent_redirect | | Client Error | 400 | :bad_request | | | 401 | :unauthorized | | | 402 | :payment_required | | | 403 | :forbidden | | | 404 | :not_found | | | 405 | :method_not_allowed | | | 406 | :not_acceptable | | | 407 | :proxy_authentication_required | | | 408 | :request_timeout | | | 409 | :conflict | | | 410 | :gone | | | 411 | :length_required | | | 412 | :precondition_failed | | | 413 | :request_entity_too_large | | | 414 | :request_uri_too_long | | | 415 | :unsupported_media_type | | | 416 | :requested_range_not_satisfiable | | | 417 | :expectation_failed | | | 422 | :unprocessable_entity | | | 423 | :locked | | | 424 | :failed_dependency | | | 426 | :upgrade_required | | | 428 | :precondition_required | | | 429 | :too_many_requests | | | 431 | :request_header_fields_too_large | | Server Error | 500 | :internal_server_error | | | 501 | :not_implemented | | | 502 | :bad_gateway | | | 503 | :service_unavailable | | | 504 | :gateway_timeout | | | 505 | :http_version_not_supported | | | 506 | :variant_also_negotiates | | | 507 | :insufficient_storage | | | 508 | :loop_detected | | | 510 | :not_extended | | | 511 | :network_authentication_required |
Finding Layouts¶ ↑
To find the current layout, Rails first looks for a file in
app/views/layouts
with the same base name as the controller.
For example, rendering actions from the PhotosController
class
will use app/views/layouts/photos.html.erb
(or
app/views/layouts/photos.builder
). If there is no such
controller-specific layout, Rails will use
app/views/layouts/application.html.erb
or
app/views/layouts/application.builder
. If there is no
.erb
layout, Rails will use a .builder
layout if
one exists. Rails also provides several ways to more precisely assign
specific layouts to individual controllers and actions.
Specifying Layouts for Controllers¶ ↑
You can override the default layout conventions in your controllers by
using the layout
declaration. For example:
class ProductsController < ApplicationController layout "inventory" #... end
With this declaration, all of the views rendered by the
ProductsController
will use
app/views/layouts/inventory.html.erb
as their layout.
To assign a specific layout for the entire application, use a
layout
declaration in your ApplicationController
class:
class ApplicationController < ActionController::Base layout "main" #... end
With this declaration, all of the views in the entire application will use
app/views/layouts/main.html.erb
for their layout.
Choosing Layouts at Runtime¶ ↑
You can use a symbol to defer the choice of layout until a request is processed:
class ProductsController < ApplicationController layout :products_layout def show @product = Product.find(params[:id]) end private def products_layout @current_user.special? ? "special" : "products" end end
Now, if the current user is a special user, they'll get a special layout when viewing a product.
You can even use an inline method, such as a Proc, to determine the layout.
For example, if you pass a Proc object, the block you give the Proc will be
given the controller
instance, so the layout can be determined
based on the current request:
class ProductsController < ApplicationController layout Proc.new { |controller| controller.request.xhr? ? "popup" : "application" } end
Conditional Layouts¶ ↑
Layouts specified at the controller level support the :only
and :except
options. These options take either a method name,
or an array of method names, corresponding to method names within the
controller:
class ProductsController < ApplicationController layout "product", except: [:index, :rss] end
With this declaration, the product
layout would be used for
everything but the rss
and index
methods.
Layout Inheritance¶ ↑
Layout declarations cascade downward in the hierarchy, and more specific layout declarations always override more general ones. For example:
-
application_controller.rb
class ApplicationController < ActionController::Base layout "main" end
-
articles_controller.rb
class ArticlesController < ApplicationController end
-
special_articles_controller.rb
class SpecialArticlesController < ArticlesController layout "special" end
-
old_articles_controller.rb
class OldArticlesController < SpecialArticlesController layout false def show @article = Article.find(params[:id]) end def index @old_articles = Article.older render layout: "old" end # ... end
In this application:
-
In general, views will be rendered in the
main
layout -
ArticlesController#index
will use themain
layout -
SpecialArticlesController#index
will use thespecial
layout -
OldArticlesController#show
will use no layout at all -
OldArticlesController#index
will use theold
layout
Avoiding Double Render Errors¶ ↑
Sooner or later, most Rails developers will see the error message “Can only
render or redirect once per action”. While this is annoying, it's
relatively easy to fix. Usually it happens because of a fundamental
misunderstanding of the way that render
works.
For example, here's some code that will trigger this error:
def show @book = Book.find(params[:id]) if @book.special? render action: "special_show" end render action: "regular_show" end
If @book.special?
evaluates to true
, Rails will
start the rendering process to dump the @book
variable into
the special_show
view. But this will not stop the
rest of the code in the show
action from running, and when
Rails hits the end of the action, it will start to render the
regular_show
view - and throw an error. The solution is
simple: make sure that you have only one call to render
or
redirect
in a single code path. One thing that can help is
and return
. Here's a patched version of the method:
def show @book = Book.find(params[:id]) if @book.special? render action: "special_show" and return end render action: "regular_show" end
Make sure to use and return
instead of &&
return
because && return
will not work due to
the operator precedence in the Ruby Language.
Note that the implicit render done by ActionController detects if
render
has been called, so the following will work without
errors:
def show @book = Book.find(params[:id]) if @book.special? render action: "special_show" end end
This will render a book with special?
set with the
special_show
template, while other books will render with the
default show
template.
Using redirect_to
¶ ↑
Another way to handle returning responses to an HTTP request is with
redirect_to
. As you've seen, render
tells
Rails which view (or other asset) to use in constructing a response. The
redirect_to
method does something completely different: it
tells the browser to send a new request for a different URL. For example,
you could redirect from wherever you are in your code to the index of
photos in your application with this call:
redirect_to photos_url
You can use redirect_to
with any arguments that you could use
with link_to
or url_for
. There's also a
special redirect that sends the user back to the page they just came from:
redirect_to :back
Getting a Different Redirect Status Code¶ ↑
Rails uses HTTP status code 302, a temporary redirect, when you call
redirect_to
. If you'd like to use a different status code,
perhaps 301, a permanent redirect, you can use the :status
option:
redirect_to photos_path, status: 301
Just like the :status
option for render
,
:status
for redirect_to
accepts both numeric and
symbolic header designations.
The Difference Between render
and redirect_to
¶ ↑
Sometimes inexperienced developers think of redirect_to
as a
sort of goto
command, moving execution from one place to
another in your Rails code. This is not correct. Your code stops
running and waits for a new request for the browser. It just happens that
you've told the browser what request it should make next, by sending
back an HTTP 302 status code.
Consider these actions to see the difference:
def index @books = Book.all end def show @book = Book.find_by(id: params[:id]) if @book.nil? render action: "index" end end
With the code in this form, there will likely be a problem if the
@book
variable is nil
. Remember, a render
:action
doesn't run any code in the target action, so nothing
will set up the @books
variable that the index
view will probably require. One way to fix this is to redirect instead of
rendering:
def index @books = Book.all end def show @book = Book.find_by(id: params[:id]) if @book.nil? redirect_to action: :index end end
With this code, the browser will make a fresh request for the index page,
the code in the index
method will run, and all will be well.
The only downside to this code is that it requires a round trip to the
browser: the browser requested the show action with /books/1
and the controller finds that there are no books, so the controller sends
out a 302 redirect response to the browser telling it to go to
/books/
, the browser complies and sends a new request back to
the controller asking now for the index
action, the controller
then gets all the books in the database and renders the index template,
sending it back down to the browser which then shows it on your screen.
While in a small application, this added latency might not be a problem, it is something to think about if response time is a concern. We can demonstrate one way to handle this with a contrived example:
def index @books = Book.all end def show @book = Book.find_by(id: params[:id]) if @book.nil? @books = Book.all flash.now[:alert] = "Your book was not found" render "index" end end
This would detect that there are no books with the specified ID, populate
the @books
instance variable with all the books in the model,
and then directly render the index.html.erb
template,
returning it to the browser with a flash alert message to tell the user
what happened.
Using head
To Build Header-Only Responses¶ ↑
The head
method can be used to send responses with only
headers to the browser. It provides a more obvious alternative to calling
render :nothing
. The head
method accepts a number
or symbol (see reference table)
representing a HTTP status code. The options argument is interpreted as a
hash of header names and values. For example, you can return only an error
header:
head :bad_request
This would produce the following header:
HTTP/1.1 400 Bad Request Connection: close Date: Sun, 24 Jan 2010 12:15:53 GMT Transfer-Encoding: chunked Content-Type: text/html; charset=utf-8 X-Runtime: 0.013483 Set-Cookie: _blog_session=...snip...; path=/; HttpOnly Cache-Control: no-cache
Or you can use other HTTP headers to convey other information:
head :created, location: photo_path(@photo)
Which would produce:
HTTP/1.1 201 Created Connection: close Date: Sun, 24 Jan 2010 12:16:44 GMT Transfer-Encoding: chunked Location: /photos/1 Content-Type: text/html; charset=utf-8 X-Runtime: 0.083496 Set-Cookie: _blog_session=...snip...; path=/; HttpOnly Cache-Control: no-cache
Structuring Layouts¶ ↑
When Rails renders a view as a response, it does so by combining the view with the current layout, using the rules for finding the current layout that were covered earlier in this guide. Within a layout, you have access to three tools for combining different bits of output to form the overall response:
-
Asset tags
-
yield
andcontent_for
-
Partials
Asset Tag Helpers¶ ↑
Asset tag helpers provide methods for generating HTML that link views to feeds, JavaScript, stylesheets, images, videos and audios. There are six asset tag helpers available in Rails:
-
auto_discovery_link_tag
-
javascript_include_tag
-
stylesheet_link_tag
-
image_tag
-
video_tag
-
audio_tag
You can use these tags in layouts or other views, although the
auto_discovery_link_tag
, javascript_include_tag
,
and stylesheet_link_tag
, are most commonly used in the

section of a layout.
WARNING: The asset tag helpers do not verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link.
Linking to Feeds with the auto_discovery_link_tag
¶ ↑
The auto_discovery_link_tag
helper builds HTML that most
browsers and feed readers can use to detect the presence of RSS or Atom
feeds. It takes the type of the link (:rss
or
:atom
), a hash of options that are passed through to url_for,
and a hash of options for the tag:
<%= auto_discovery_link_tag(:rss, {action: "feed"}, {title: "RSS Feed"}) %>
There are three tag options available for the
auto_discovery_link_tag
:
-
:rel
specifies therel
value in the link. The default value is “alternate”. -
:type
specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically. -
:title
specifies the title of the link. The default value is the uppercase:type
value, for example, “ATOM” or “RSS”.
Linking to JavaScript Files with the javascript_include_tag
¶ ↑
The javascript_include_tag
helper returns an HTML
script
tag for each source provided.
If you are using Rails with the Asset
Pipeline enabled, this helper will generate a link to
/assets/javascripts/
rather than
public/javascripts
which was used in earlier versions of
Rails. This link is then served by the asset pipeline.
A JavaScript file within a Rails application or Rails engine goes in one of
three locations: app/assets
, lib/assets
or
vendor/assets
. These locations are explained in detail in the
Asset Organization section
in the Asset Pipeline Guide
You can specify a full path relative to the document root, or a URL, if you
prefer. For example, to link to a JavaScript file that is inside a
directory called javascripts
inside of one of
app/assets
, lib/assets
or
vendor/assets
, you would do this:
<%= javascript_include_tag "main" %>
Rails will then output a script
tag such as this:

The request to this asset is then served by the Sprockets gem.
To include multiple files such as
app/assets/javascripts/main.js
and
app/assets/javascripts/columns.js
at the same time:
<%= javascript_include_tag "main", "columns" %>
To include app/assets/javascripts/main.js
and
app/assets/javascripts/photos/columns.js
:
<%= javascript_include_tag "main", "/photos/columns" %>
To include http://example.com/main.js
:
<%= javascript_include_tag "http://example.com/main.js" %>
Linking to CSS Files with the stylesheet_link_tag
¶ ↑
The stylesheet_link_tag
helper returns an HTML
<link>
tag for each source provided.
If you are using Rails with the “Asset Pipeline” enabled, this helper will
generate a link to /assets/stylesheets/
. This link is then
processed by the Sprockets gem. A stylesheet file can be stored in one of
three locations: app/assets
, lib/assets
or
vendor/assets
.
You can specify a full path relative to the document root, or a URL. For
example, to link to a stylesheet file that is inside a directory called
stylesheets
inside of one of app/assets
,
lib/assets
or vendor/assets
, you would do this:
<%= stylesheet_link_tag "main" %>
To include app/assets/stylesheets/main.css
and
app/assets/stylesheets/columns.css
:
<%= stylesheet_link_tag "main", "columns" %>
To include app/assets/stylesheets/main.css
and
app/assets/stylesheets/photos/columns.css
:
<%= stylesheet_link_tag "main", "photos/columns" %>
To include http://example.com/main.css
:
<%= stylesheet_link_tag "http://example.com/main.css" %>
By default, the stylesheet_link_tag
creates links with
media="screen" rel="stylesheet"
. You can
override any of these defaults by specifying an appropriate option
(:media
, :rel
):
<%= stylesheet_link_tag "main_print", media: "print" %>
Linking to Images with the image_tag
¶ ↑
The image_tag
helper builds an HTML
tag to the specified file. By default, files are loaded from
public/images
.
WARNING: Note that you must specify the extension of the image.
<%= image_tag "header.png" %>
You can supply a path to the image if you like:
<%= image_tag "icons/delete.gif" %>
You can supply a hash of additional HTML options:
<%= image_tag "icons/delete.gif", {height: 45} %>
You can supply alternate text for the image which will be used if the user has images turned off in their browser. If you do not specify an alt text explicitly, it defaults to the file name of the file, capitalized and with no extension. For example, these two image tags would return the same code:
<%= image_tag "home.gif" %> <%= image_tag "home.gif", alt: "Home" %>
You can also specify a special size tag, in the format “{width}x{height}”:
<%= image_tag "home.gif", size: "50x20" %>
In addition to the above special tags, you can supply a final hash of
standard HTML options, such as :class
, :id
or
:name
:
<%= image_tag "home.gif", alt: "Go Home", id: "HomeImage", class: "nav_bar" %>
Linking to Videos with the video_tag
¶ ↑
The video_tag
helper builds an HTML 5
<video>
tag to the specified file. By default, files are
loaded from public/videos
.
<%= video_tag "movie.ogg" %>
Produces
<video src="/videos/movie.ogg" />
Like an image_tag
you can supply a path, either absolute, or
relative to the public/videos
directory. Additionally you can
specify the size: "#{width}x#{height}"
option just
like an image_tag
. Video tags can also have any of the HTML
options specified at the end (id
, class
et al).
The video tag also supports all of the <video>
HTML
options through the HTML options hash, including:
-
poster: "image_name.png"
, provides an image to put in place of the video before it starts playing. -
autoplay: true
, starts playing the video on page load. -
loop: true
, loops the video once it gets to the end. -
controls: true
, provides browser supplied controls for the user to interact with the video. -
autobuffer: true
, the video will pre load the file for the user on page load.
You can also specify multiple videos to play by passing an array of videos
to the video_tag
:
<%= video_tag ["trailer.ogg", "movie.ogg"] %>
This will produce:
<video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
Linking to Audio Files with the audio_tag
¶ ↑
The audio_tag
helper builds an HTML 5
<audio>
tag to the specified file. By default, files are
loaded from public/audios
.
<%= audio_tag "music.mp3" %>
You can supply a path to the audio file if you like:
<%= audio_tag "music/first_song.mp3" %>
You can also supply a hash of additional options, such as :id
,
:class
etc.
Like the video_tag
, the audio_tag
has special
options:
-
autoplay: true
, starts playing the audio on page load -
controls: true
, provides browser supplied controls for the user to interact with the audio. -
autobuffer: true
, the audio will pre load the file for the user on page load.
Understanding yield
¶ ↑
Within the context of a layout, yield
identifies a section
where content from the view should be inserted. The simplest way to use
this is to have a single yield
, into which the entire contents
of the view currently being rendered is inserted:
    <%= yield %>
You can also create a layout with multiple yielding regions:
  <%= yield :head %>   <%= yield %>
The main body of the view will always render into the unnamed
yield
. To render content into a named yield
, you
use the content_for
method.
Using the content_for
Method¶ ↑
The content_for
method allows you to insert content into a
named yield
block in your layout. For example, this view would
work with the layout that you just saw:
<% content_for :head do %> <title>A simple page</title> <% end %>
Hello, Rails!

The result of rendering this page into the supplied layout would be this HTML:
  <title>A simple page</title>
Hello, Rails!

The content_for
method is very helpful when your layout
contains distinct regions such as sidebars and footers that should get
their own blocks of content inserted. It's also useful for inserting
tags that load page-specific JavaScript or css files into the header of an
otherwise generic layout.
Using Partials¶ ↑
Partial templates - usually just called “partials” - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
Naming Partials¶ ↑
To render a partial as part of a view, you use the render
method within the view:
<%Q= render "menu" %>
This will render a file named _menu.html.erb
at that point
within the view being rendered. Note the leading underscore character:
partials are named with a leading underscore to distinguish them from
regular views, even though they are referred to without the underscore.
This holds true even when you're pulling in a partial from another
folder:
<%Q= render "shared/menu" %>
That code will pull in the partial from
app/views/shared/_menu.html.erb
.
Using Partials to Simplify Views¶ ↑
One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looked like this:
<%= render "shared/ad_banner" %>
Products

Here are a few of our fine products:
 ... <%= render "shared/footer" %>
Here, the _ad_banner.html.erb
and
_footer.html.erb
partials could contain content that is shared
among many pages in your application. You don't need to see the details
of these sections when you're concentrating on a particular page.
TIP: For content that is shared among all pages in your application, you can use partials directly from layouts.
Partial Layouts¶ ↑
A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this:
<%= render partial: "link_area", layout: "graybar" %>
This would look for a partial named _link_area.html.erb
and
render it using the layout _graybar.html.erb
. Note that
layouts for partials follow the same leading-underscore naming as regular
partials, and are placed in the same folder with the partial that they
belong to (not in the master layouts
folder).
Also note that explicitly specifying :partial
is required when
passing additional options such as :layout
.
Passing Local Variables¶ ↑
You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:
-
new.html.erb

New zone
 <%= render partial: "form", locals: {zone: @zone} %>
-
edit.html.erb

Editing zone
 <%= render partial: "form", locals: {zone: @zone} %>
-
_form.html.erb
<%= form_for(zone) do |f| %>
 Zone name
 <%= f.text_field :name %>

 <%= f.submit %>
 <% end %>
Although the same partial will be rendered into both views, Action View's submit helper will return “Create Zone” for the new action and “Update Zone” for the edit action.
Every partial also has a local variable with the same name as the partial
(minus the underscore). You can pass an object in to this local variable
via the :object
option:
<%= render partial: "customer", object: @new_customer %>
Within the customer
partial, the customer
variable will refer to @new_customer
from the parent view.
If you have an instance of a model to render into a partial, you can use a shorthand syntax:
<%= render @customer %>
Assuming that the @customer
instance variable contains an
instance of the Customer
model, this will use
_customer.html.erb
to render it and will pass the local
variable customer
into the partial which will refer to the
@customer
instance variable in the parent view.
Rendering Collections¶ ↑
Partials are very useful in rendering collections. When you pass a
collection to a partial via the :collection
option, the
partial will be inserted once for each member in the collection:
-
index.html.erb

Products
 <%= render partial: "product", collection: @products %>
-
_product.html.erb

Product Name: <%= product.name %>

When a partial is called with a pluralized collection, then the individual
instances of the partial have access to the member of the collection being
rendered via a variable named after the partial. In this case, the partial
is _product
, and within the _product
partial, you
can refer to product
to get the instance that is being
rendered.
There is also a shorthand for this. Assuming @products
is a
collection of product
instances, you can simply write this in
the index.html.erb
to produce the same result:

Products
 <%= render @products %>
Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection:
-
index.html.erb

Contacts
 <%= render [customer1, employee1, customer2, employee2] %>
-
customers/_customer.html.erb

Customer: <%= customer.name %>

-
employees/_employee.html.erb

Employee: <%= employee.name %>

In this case, Rails will use the customer or employee partials as appropriate for each member of the collection.
In the event that the collection is empty, render
will return
nil, so it should be fairly simple to provide alternative content.

Products
 <%= render(@products) || "There are no products available." %>
Local Variables¶ ↑
To use a custom local variable name within the partial, specify the
:as
option in the call to the partial:
<%= render partial: "product", collection: @products, as: :item %>
With this change, you can access an instance of the @products
collection as the item
local variable within the partial.
You can also pass in arbitrary local variables to any partial you are
rendering with the locals: {}
option:
<%= render partial: "product", collection: @products, as: :item, locals: {title: "Products Page"} %>
In this case, the partial will have access to a local variable
title
with the value “Products Page”.
TIP: Rails also makes a counter variable available within a partial called
by the collection, named after the member of the collection followed by
_counter
. For example, if you're rendering
@products
, within the partial you can refer to
product_counter
to tell you how many times the partial has
been rendered. This does not work in conjunction with the as:
:value
option.
You can also specify a second partial to be rendered between instances of
the main partial by using the :spacer_template
option:
Spacer Templates¶ ↑
<%= render partial: @products, spacer_template: "product_ruler" %>
Rails will render the _product_ruler
partial (with no data
passed in to it) between each pair of _product
partials.
Collection Partial Layouts¶ ↑
When rendering collections it is also possible to use the
:layout
option:
<%= render partial: "product", collection: @products, layout: "special_layout" %>
The layout will be rendered together with the partial for each item in the collection. The current object and object_counter variables will be available in the layout as well, the same way they do within the partial.
Using Nested Layouts¶ ↑
You may find that your application requires a layout that differs slightly from your regular application layout to support one particular controller. Rather than repeating the main layout and editing it, you can accomplish this by using nested layouts (sometimes called sub-templates). Here's an example:
Suppose you have the following ApplicationController
layout:
-
app/views/layouts/application.html.erb
  <title><%= @page_title or "Page Title" %></title> <%= stylesheet_link_tag "layout" %>
Top menu items here

Menu items here

<%= content_for?(:content) ? yield(:content) : yield %>

On pages generated by NewsController
, you want to hide the top
menu and add a right menu:
-
app/views/layouts/news.html.erb
<% content_for :stylesheets do %> #top_menu {display: none} #right_menu {float: right; background-color: yellow; color: black} <% end %> <% content_for :content do %>
Right menu items here
 <%= content_for?(:news_content) ? yield(:news_content) : yield %> <% end %> <%= render template: "layouts/application" %>
That's it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the “content” div.
There are several ways of getting similar results with different
sub-templating schemes using this technique. Note that there is no limit in
nesting levels. One can use the ActionView::render
method via
render template: 'layouts/news'
to base a new layout
on the News layout. If you are sure you will not subtemplate the
News
layout, you can replace the
content_for?(:news_content) ? yield(:news_content) : yield
with simply yield
.


We are a non‑profit association because we believe in a free, world-class chess experience for anyone, anywhere.
We rely on support from people like you to make it possible. If you've gotten something out of lichess, please take a second to pitch in!


Two PIA flights land safely after developing technical issues
by Our CorrespondentISLAMABAD/LAHORE: Two Pakistan International Airline (PIA) flights landed safely after technical issues developed during flights to their destinations.
The engine of flight PK-650, enroute from Lahore to Islamabad, malfunctioned and shut down after reportedly ingesting a foreign object.
The pilot switched the engine off and landed the plane safely.
There were 38 passengers onboard besides the PIA staff, all of whom remained unhurt in the incident.
Another PIA flight, PK-257, developed a fault in its landing gear soon after takeoff. The aircraft was travelling from Peshawar to Sharjah.
Reportedly soon after takeoff from Bacha Khan International Airport, certain aircraft systems crashed. The system crash also affected the autopilot, auto thrust and other sub-systems.
After repeated attempts to close the landing gear, the pilot swerved around and landed back at Peshawar airport. More than 100 passengers were onboard.
After landing, PIA engineers conducted a detailed inspection of the aircraft at Peshawar airport but failed to resolve the technical problem.
In July, A PIA flight survived a scare as the plane skidded off the runway while landing at the Gilgit airport.
“The ATR-42 aircraft skidded a little off an unpaved patch. The pilots exhibited great skill and composure to regain control and ensure everyone’s safety,” said a spokesperson for the national flag carrier.
Over the past years, there have been recurring safety issues with PIA flights in the country’s northern areas.


Redis_2_0_Whats_new
The release of Redis 2.0 marks a major milestone in Redis development. Apart from an endless list of new features, there are some major ones that deserve to be highlighted.
The MULTI/EXEC family of commands were added to fulfill the need to execute multiple commands as a single atomic block.
Because all commands inside a MULTI/EXEC block are serialized and executed sequentially, it is not possible that another
client request is served in the middle of executing this block. All commands are executed one after the other when
EXEC is called, which makes sure either
all or
no commands are executed, independent of the state of the client connection.
More on MULTI/EXEC:
The commands BLPOP and BRPOP were added to support popping from a list in a blocking fashion. This means the client
connection will be blocked for a certain amount of time until another client pushes an item on a list. These commands
are frequently used in producer/consumer scenarios.
More on blocking pop:
The family of publish/subscribe commands let clients publish messages onto channels and subscribe to receive all messages
that are published on channels. Also included are commands to receive all messages for which the channel matches a given pattern.
More on publish/subscribe:
This new datatype allows to store multiple key/value pairs on a single key. Together with the list of regular commands you
would expect for such a datatype (HSET, HGET, HDEL, HLEN, HKEYS, ...), it is also possible to use the values
inside a hash
for any SORT operation.
More on hashes:
Redis Virtual Memory allows users to grow their dataset beyond the limits of their RAM.
More on virtual memory:
- Salvatore Sanfilippo
- Pieter Noordhuis
- Antonio Ognio
- Alex McHale
- Michel Martens
- Damian Janowski
- Bruno Deferrari
- Ashley Martens
- Derek Collison
- Damian Janowski
- Jeremy Zawodny
- Konstantin Merenkov
- Michel Martens
- Sam Hendley


Preparation time
less than 30 mins
Cooking time
1 to 2 hours
Serves
Serves 6
The secret of success in this recipe is to leave the lamb to cook on a very low heat. Serve this springtime dish with plenty of bread to mop up the sauce.
Season the lamb chunks with salt and black pepper. Set aside.
Heat the olive oil in a large lidded pan and fry the onions, carrot and celery for 4–5 minutes, or until softened. Add the garlic, anchovies, thyme and chilli, and continue to cook, stirring, until the anchovies have almost dissolved into the oil. Add the lamb chunks and fry for a further 4–5 minutes, or until browned all over.
Stir in the wine and continue to cook until the volume of the liquid has reduced by half, then add the vinegar. Reduce the heat to low, cover and simmer gently for 20 minutes.
Add the peas, potatoes and tomatoes, cover again and continue to cook for about an hour, until the sauce has reduced by half.
Serve hot with plenty of bread to mop up the sauce.