Hanami is built for people like you.

I warn you that whether you’re a total beginner or an experienced developer this learning process can be hard. Over time, we build expectations about how things should be, and it can be painful to change. But without change, there is no challenge and without challenge, there is no growth.

Sometimes a feature doesn’t look right, that doesn’t mean it’s you. It can be a matter of formed habits, a design fallacy or even a bug.

Myself and the rest of the Community are putting best efforts to make Hanami better every day.

In this guide we will set up our first Hanami project and build a simple bookshelf web application. We’ll touch on all the major components of Hanami framework, all guided by tests.

If you feel alone, or frustrated, don’t give up, jump in our chat and ask for help. There will be someone more than happy to talk with you.

Enjoy,
Luca Guidi
Hanami creator


Before we get started, let’s get some prerequisites out of the way. First, we’re going to assume a basic knowledge of developing web applications.

You should also be familiar with Bundler, , working with a terminal and building apps using the Model, View, Controller paradigm.

Lastly, in this guide, we’ll be using an database. If you want to follow along, make sure you have a working installation of Ruby 2.3+ and SQLite 3+ on your system.

This guide is for the latest release of Hanami: v1.3.

We, the Hanami core team, are working on the next major version of Hanami: v2.0.

That said, Hanami v1.3 only supports Ruby 2.3–2.7. It does not support Ruby 3.

So, to continue with this guide, you have to be using Ruby 2.

(Hanami v2.0 will support Ruby 3, of course.)

Create a New Hanami Project

To create a new Hanami project, we need to install the Hanami gem from Rubygems. Then we can use the new executable to generate a new project:

By default, the project will be setup to use a SQLite database. For real-world projects, you can specify your engine:
$ hanami new bookshelf --database=postgres

This creates a new directory bookshelf in our current location. Let’s see what it contains:

  1. $ cd bookshelf
  2. $ tree -L 1
  3. .
  4. ├── Gemfile
  5. ├── README.md
  6. ├── Rakefile
  7. ├── apps
  8. ├── config
  9. ├── config.ru
  10. ├── db
  11. ├── lib
  12. ├── public
  13. └── spec
  14. 6 directories, 4 files

Here’s what we need to know:

  • Gemfile defines our Rubygems dependencies (using Bundler).
  • README.md tells us how to set up and use the project.
  • Rakefile describes our Rake tasks.
  • apps contains one or more web applications compatible with Rack, where we can find the first generated Hanami application called web. It’s the place where we find our controllers, views, routes and, templates.
  • config contains configuration files.
  • config.ru is for Rack servers.
  • db contains our database schema and migrations.
  • lib contains our business logic and domain model, including entities and repositories.
  • public will contain compiled static assets.
  • spec contains our tests.

Go ahead and install our gem dependencies with Bundler; then we can launch a development server:

  1. $ bundle install
  2. $ bundle exec hanami server

And… bask in the glory of your first Hanami project at ! We should see a screen similar to this:

Hanami’s architecture revolves around your project containing many apps. These all live together in the same codebase, and exist in the same Ruby process.

They live under apps/.

By default, we have a web app, which can be thought of as the standard, user-facing web interface. This is the most popular, so you’ll probably want to keep it in your future Hanami projects. However, there’s nothing unique about this app, it’s just so common that Hanami generates it for us.

Later (in a real project), we would add other apps, such as an admin panel, a JSON api, or an analytics dashboard. We could also break our web app into smaller parts, extracting isolated pieces of functionality. Hanami fully supports that, too!

Different apps represent delivery mechanisms. That means they’re different ways of interacting with the core of your project, or the “business logic”.

Hanami doesn’t want us to therefore “business logic” is shared. Web applications almost always store and interact with data stored in a database. Both our “business logic” and our persistence live in lib/.

(Hanami architecture is heavily inspired by Hexagonal architecture).)

Writing Our First Test

The opening screen we see when we point our browser at our app is a default page which is displayed when there are no routes defined.

Hanami encourages Behavior Driven Development (BDD) as a way to write web applications. To get our first custom page to display, we’ll write a high-level feature test:

  1. # spec/web/features/visit_home_spec.rb
  2. require 'features_helper'
  3. RSpec.describe 'Visit home' do
  4. it 'is successful' do
  5. visit '/'
  6. expect(page).to have_content('Bookshelf')
  7. end
  8. end

Hanami is ready for a Behavior Driven Development (BDD) workflow out of the box, but it is in no way bound to any particular testing framework. It does not come with any special testing integrations or libraries, so if you know RSpec (or Minitest), there’s nothing new to learn there.

We have to migrate our schema in the test database by running:

  1. $ HANAMI_ENV=test bundle exec hanami db prepare

The HANAMI_ENV at the beginning is an environment variable, which tells Hanami to use the test environment. This is necessary here because the default is HANAMI_ENV=development.

If you have trouble, your DATABASE_URL is defined in .env.test

Now we have a test; we can see it fail:

  1. $ bundle exec rake
  2. F.
  3. Failures:
  4. 1) Visit home is successful
  5. Failure/Error: expect(page).to have_content('Bookshelf')
  6. expected to find text "Bookshelf" in "404 - Not Found"
  7. # ./spec/web/features/visit_home_spec.rb:7:in `block (2 levels) in <top (required)>'
  8. Finished in 0.02604 seconds (files took 1.14 seconds to load)
  9. 2 examples, 1 failure
  10. Failed examples:
  11. rspec ./spec/web/features/visit_home_spec.rb:4 # Visit home is successful

Now let’s make it pass. We’ll add the code required to make this test pass, step-by-step.

The first thing we need to add is a route:

  1. # apps/web/config/routes.rb
  2. root to: 'home#index'

We pointed our app’s root URL to the index action of the home controller (see the routing guide for more information).

If we run our tests, we’ll get a Hanami::Routing::EndpointNotFound error.

That makes sense because we need to create the home#index action.

  1. # apps/web/controllers/home/index.rb
  2. module Web
  3. module Controllers
  4. module Home
  5. class Index
  6. include Web::Action
  7. def call(params)
  8. end
  9. end
  10. end
  11. end
  12. end

This is an empty action that doesn’t do anything special. Each action in Hanami is defined by , which makes it simple to test. Moreover, each action has a corresponding view, which is also defined by its class. This one needs to be added in order to complete the request.

  1. # apps/web/views/home/index.rb
  2. module Web
  3. module Views
  4. module Home
  5. class Index
  6. include Web::View
  7. end
  8. end
  9. end
  10. end

It’s also empty and doesn’t do anything special. Its only responsibility is to render a template, which is what views do by default.

This template is what we need to add, to make our tests pass. All we need to do is add the bookshelf heading.

  1. # apps/web/templates/home/index.html.erb
  2. <h1>Bookshelf</h1>

Now let’s run our test suite again.

  1. $ bundle exec rake
  2. Finished in 0.01394 seconds (files took 1.03 seconds to load)
  3. 2 examples, 0 failures

This means all our tests pass!

Let’s use our new knowledge about Hanami routes, actions, views, and templates.

We’ll store books in our database and let the user manage them with our project.

Our first step is to list out all the books we know about.

Let’s write a new feature test describing what we want to achieve:

  1. # spec/web/features/list_books_spec.rb
  2. require 'features_helper'
  3. RSpec.describe 'List books' do
  4. it 'displays each book on the page' do
  5. visit '/books'
  6. within '#books' do
  7. expect(page).to have_css('.book', count: 2)
  8. end
  9. end
  10. end

This test means that when we go to , we’ll see two HTML elements that have class book, and both will be inside of an HTML element that has an id of books.

Our test suite shows 1 failure: Unable to find visible css "#books".

Not only are we missing that element, we don’t even have a page to put that element on!

Let’s create a new action and a new route to fix that.

Hanami Generators

Hanami ships with a number of generators, which are tools that write some code for you.

In our terminal, let’s run:

  1. $ bundle exec hanami generate action web books#index

If you’re using ZSH and that doesn’t work (with an error like zsh: no matches found: books#index), Hanami lets us write this instead: hanami generate action web books/index

This does a lot for us:

  • Creating an action at apps/web/controllers/books/index.rb (and spec for it),
  • Creating a view at apps/web/views/books/index.rb (and a spec for it),
  • Creating a template at apps/web/templates/books/index.html.erb.

(If you’re confused by ‘action’ vs. ‘controller’: Hanami only has action classes, so a controller is just a module to group several related actions together.)

These files are all pretty much empty. They have some basic code in there, so Hanami knows how to use the class. Thankfully we don’t have to manually create those five files, with that specific code in them.

The generator also adds a new route for us in the web app’s routes file (apps/web/config/routes.rb).

  1. get '/books', to: 'books#index'

To make our tests pass, we need to edit our newly generated template file in apps/web/templates/books/index.html.erb:

  1. <h1>Bookshelf</h1>
  2. <h2>All books</h2>
  3. <div id="books">
  4. <div class="book">
  5. <h3>Patterns of Enterprise Application Architecture</h3>
  6. <p>by <strong>Martin Fowler</strong></p>
  7. </div>
  8. <div class="book">
  9. <h3>Test Driven Development</h3>
  10. <p>by <strong>Kent Beck</strong></p>
  11. </div>
  12. </div>

Now our tests pass!

We’ve used a generator to create a new end-point (page) in our application.

But, we’ve started to repeat ourselves.

In both our books/index.html.erb template, and our home/index.html.erb template from above, we have <h1>Bookshelf</h1>.

This is not a huge deal, but in a real application, we’ll likely have a logo or common navigation shared across all of the pages in our app.

Let’s fix that repetition, to show how that works.

Layouts

To avoid repeating ourselves in every single template, we can modify our layout template. Let’s edit apps/web/templates/application.html.erb to look like this:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Web</title>
  5. <%= favicon %>
  6. </head>
  7. <body>
  8. <h1>Bookshelf</h1>
  9. <%= yield %>
  10. </body>
  11. </html>

And remove the <h1>Bookshelf</h1> line from the other templates (apps/web/templates/home/index.html.erb, apps/web/templates/books/index.html.erb), so it’s not duplicated.

A layout template is like any other template, but it is used to wrap your regular templates. The yield line is replaced with the contents of our regular template. It’s the perfect place to put our repeating headers and footers.

Modeling Our Data With Entities

Hard-coding books in our templates is, admittedly, kind of cheating. Let’s add some dynamic data to our application!

We’ll store books in our database and display them on our page. To do so, we need a way to read and write to our database. There are two types of objects that we’ll use for this:

  • an entity is a domain object (a Book) that is uniquely identified by its identity,
  • a repository is what we use to persist, retrieve, and delete data for an entity, in the persistence layer.

Entities are entirely unaware of the database. This makes them lightweight and easy to test.

Since entities are completely decoupled from the database, we use repositories to persist the data behind a Book.

(We also use repositories to turn the data from the database back into a Book, and delete that data, too.)

Read more about entities and repositories in the .

Hanami ships with a generator for models, so let’s use it to create a Book entity and its corresponding repository:

  1. $ bundle exec hanami generate model book
  2. create lib/bookshelf/entities/book.rb
  3. create lib/bookshelf/repositories/book_repository.rb
  4. create db/migrations/20181024110038_create_books.rb
  5. create spec/bookshelf/entities/book_spec.rb
  6. create spec/bookshelf/repositories/book_repository_spec.rb

The generator gives us an entity, a repository, and their associated test files.

It also gives a database migration.

Migrations To Change Our Database Schema

Let’s modify the generated migration to include title and author fields:

Hanami provides a DSL to describe changes to our database schema. You can read more about how migrations work in the .

In this case, we define a new table with columns for each of our entities’ attributes. Let’s prepare our database for the development and test environments:

  1. $ bundle exec hanami db prepare
  2. $ HANAMI_ENV=test bundle exec hanami db prepare

An entity is something really close to a plain Ruby object. We use them to model the behavior we want from a concept (a book, in this case). They’re decoupled from persistence entirely, but they’re easy to persist and retrieve as we’ll soon see.

For now, we need to create a simple entity class:

  1. # lib/bookshelf/entities/book.rb
  2. class Book < Hanami::Entity
  3. end

This class will generate getters and setters for each attribute we pass to initialize params. We can verify it all works as expected with a unit test:

  1. # spec/bookshelf/entities/book_spec.rb
  2. RSpec.describe Book, type: :entity do
  3. it 'can be initialized with attributes' do
  4. book = Book.new(title: 'Refactoring', author: 'Martin Fowler')
  5. expect(book.title).to eq('Refactoring')
  6. expect(book.author).to eq('Martin Fowler')
  7. end
  8. end

Generally we recommend against “testing the framework” like this in a real app, but it’s useful here to demonstrate how Entities work in Hanami.

Using Repositories

Now we are ready to play around with our repository. We can use Hanami’s console command to launch irb with our application pre-loaded, so we can use our objects:

  1. $ bundle exec hanami console
  2. >> repository = BookRepository.new
  3. # => #<BookRepository relations=[:books]>
  4. >> repository.all
  5. # => []
  6. >> book = repository.create(title: 'TDD', author: 'Kent Beck')
  7. # => #<Book:0x007f9ab61c23b8 @attributes={:id=>1, :title=>"TDD", :author=>"Kent Beck", :created_at=>2018-10-24 11:11:38 UTC, :updated_at=>2018-10-24 11:11:38 UTC}>
  8. >> repository.find(book.id)

Hanami repositories have methods to load one or more entities from our database, and to create and update existing records. The repository is also the place where you would define new methods to implement custom queries.

To recap, we’ve seen how Hanami uses entities and repositories to model our data. Entities represent our behavior, while repositories use mappings to translate our entities to and from our data store. We can use migrations to apply changes to our database schema.

Displaying Dynamic Data

With our new experience modeling data, we can get to work displaying dynamic data on our book listing page. Let’s adjust the feature test we created earlier:

  1. # spec/web/features/list_books_spec.rb
  2. require 'features_helper'
  3. RSpec.describe 'List books' do
  4. let(:repository) { BookRepository.new }
  5. before do
  6. repository.clear
  7. repository.create(title: 'Practical Object-Oriented Design in Ruby', author: 'Sandi Metz')
  8. end
  9. it 'displays each book on the page' do
  10. visit '/books'
  11. within '#books' do
  12. expect(page).to have_selector('.book', count: 1), 'Expected to find 1 book'
  13. expect(page).to have_content('Practical Object-Oriented Design in Ruby')
  14. expect(page).to have_content('Sandi Metz')
  15. end
  16. end
  17. end

We create a single Book record in our test and then expect that the title and author are displayed on the page. This test fails since we haven’t updated our template yet, and it still includes the hard-coded books from earlier.

Now we can change our template and remove the static HTML. Our view needs to loop over all available records and render them. Let’s write a test to force this change in our view:

  1. # spec/web/views/books/index_spec.rb
  2. RSpec.describe Web::Views::Books::Index, type: :view do
  3. let(:exposures) { Hash[books: []] }
  4. let(:template) { Hanami::View::Template.new('apps/web/templates/books/index.html.erb') }
  5. let(:view) { described_class.new(template, exposures) }
  6. let(:rendered) { view.render }
  7. it 'exposes #books' do
  8. expect(view.books).to eq(exposures.fetch(:books))
  9. end
  10. context 'when there are no books' do
  11. it 'shows a placeholder message' do
  12. expect(rendered).to include('<p class="placeholder">There are no books yet.</p>')
  13. end
  14. end
  15. context 'when there are books' do
  16. let(:book1) { Book.new(title: 'Refactoring', author: 'Martin Fowler') }
  17. let(:book2) { Book.new(title: 'Domain Driven Design', author: 'Eric Evans') }
  18. let(:exposures) { Hash[books: [book1, book2]] }
  19. it 'lists them all' do
  20. expect(rendered.scan(/class="book"/).length).to eq(2)
  21. expect(rendered).to include('Refactoring')
  22. expect(rendered).to include('Domain Driven Design')
  23. end
  24. it 'hides the placeholder message' do
  25. expect(rendered).to_not include('<p class="placeholder">There are no books yet.</p>')
  26. end
  27. end
  28. end

We specify that our index page will show a simple placeholder message when there are no books to display; when there are books, it lists every one of them. Note how rendering a view with some data is relatively straight-forward. Hanami is designed around simple objects with minimal interfaces that are easy to test in isolation, yet still work great together.

  1. # apps/web/templates/books/index.html.erb
  2. <h2>All books</h2>
  3. <% if books.any? %>
  4. <div id="books">
  5. <% books.each do |book| %>
  6. <div class="book">
  7. <h2><%= book.title %></h2>
  8. <p><%= book.author %></p>
  9. </div>
  10. <% end %>
  11. </div>
  12. <% else %>
  13. <p class="placeholder">There are no books yet.</p>
  14. <% end %>
  15. <a href="/books/new">New book</a>

If we run our feature test now, we’ll see it fails — because our controller action does not the books to our view. We can write a test for that change:

  1. # spec/web/controllers/books/index_spec.rb
  2. RSpec.describe Web::Controllers::Books::Index, type: :action do
  3. let(:action) { described_class.new }
  4. let(:params) { Hash[] }
  5. let(:repository) { BookRepository.new }
  6. before do
  7. repository.clear
  8. @book = repository.create(title: 'TDD', author: 'Kent Beck')
  9. end
  10. it 'is successful' do
  11. response = action.call(params)
  12. expect(response[0]).to eq(200)
  13. end
  14. it 'exposes all books' do
  15. action.call(params)
  16. expect(action.exposures[:books]).to eq([@book])
  17. end
  18. end

Writing tests for controller actions gives you two possible things to test: you either assert on the response object, which is a Rack-compatible array of status, headers, and content; or on the action itself, which will contain exposures after we’ve called it. Now we’ve specified that the action exposes :books, we can implement our action:

  1. # apps/web/controllers/books/index.rb
  2. module Web
  3. module Controllers
  4. module Books
  5. class Index
  6. include Web::Action
  7. expose :books
  8. def call(params)
  9. @books = BookRepository.new.all
  10. end
  11. end
  12. end
  13. end
  14. end

By using the expose method in our action class, we can expose the contents of our @books instance variable to the outside world, so that Hanami can pass it to the view. That’s enough to make all our tests pass again!

  1. $ bundle exec rake
  2. ......
  3. Finished in 0.03745 seconds (files took 1.34 seconds to load)
  4. 10 examples, 0 failures

One of the last remaining steps is to make it possible to add new books to the system. The plan is simple: we build a page with a form to enter details.

When the user submits the form, we build a new entity, save it, and redirect the user back to the book listing. Here’s that story expressed in a test:

  1. # spec/web/features/add_book_spec.rb
  2. require 'features_helper'
  3. RSpec.describe 'Add a book' do
  4. before do
  5. BookRepository.new.clear
  6. end
  7. it 'can create a new book' do
  8. visit '/books/new'
  9. within 'form#book-form' do
  10. fill_in 'Title', with: 'Example book'
  11. fill_in 'Author', with: 'Some author'
  12. click_button 'Create'
  13. end
  14. expect(page).to have_current_path('/books')
  15. expect(page).to have_content('Example book')
  16. end
  17. end

Laying The Foundations For A Form

By now, we should be familiar with the working of actions, views, and templates.

We’ll speed things up a little, so we can quickly get to the good parts. First, create a new action for our “New Book” page:

  1. $ bundle exec hanami generate action web books#new

This adds a new route to our app:

  1. # apps/web/config/routes.rb
  2. get '/books/new', to: 'books#new'

The interesting bit will be our new template, because we’ll be using Hanami’s form builder to construct a HTML form around our Book entity.

Let’s use to build this form in apps/web/templates/books/new.html.erb:

  1. # apps/web/templates/books/new.html.erb
  2. <h2>Add book</h2>
  3. <%=
  4. form_for :book, '/books' do
  5. div class: 'input' do
  6. label :title
  7. text_field :title
  8. end
  9. div class: 'input' do
  10. label :author
  11. text_field :author
  12. end
  13. div class: 'controls' do
  14. submit 'Create Book'
  15. end
  16. end
  17. %>

We’ve added <label> tags for our form fields, and wrapped each field in a container <div> using Hanami’s HTML builder helper.

Submitting Our Form

To submit our form, we need yet another action. Let’s create a Books::Create action:

  1. $ bundle exec hanami generate action web books#create

This adds a new route to our app:

  1. # apps/web/config/routes.rb
  2. post '/books', to: 'books#create'

Implementing Create Action

Our books#create action needs to do two things. Let’s express them as unit tests:

Making these tests pass is easy enough. We’ve already seen how we can write entities to our database, and we can use redirect_to to implement our redirection:

  1. # apps/web/controllers/books/create.rb
  2. module Web
  3. module Controllers
  4. module Books
  5. class Create
  6. include Web::Action
  7. def call(params)
  8. BookRepository.new.create(params[:book])
  9. redirect_to '/books'
  10. end
  11. end
  12. end
  13. end
  14. end

This minimal implementation should suffice to make our tests pass.

  1. $ bundle exec rake
  2. ........
  3. Finished in 0.07168 seconds (files took 1.4 seconds to load)
  4. 16 examples, 0 failures

Congratulations! We’ve created a simple web app action to add a book to a database.

Securing Our Form With Validations

Hold your horses! We need some extra measures to build a truly robust form. Imagine what would happen if the user were to submit the form without entering any values?

We could fill our database with bad data or see an exception for data integrity violations. We clearly need a way of keeping invalid data out of our system!

To express our validations in a test, we need to wonder: what would happen if our validations failed? One option would be to re-render the books#new form, so we can give our users another shot at completing it correctly. Let’s specify this behaviour as unit tests:

  1. RSpec.describe Web::Controllers::Books::Create, type: :action do
  2. let(:action) { described_class.new }
  3. before do
  4. repository.clear
  5. end
  6. context 'with valid params' do
  7. let(:params) { Hash[book: { title: 'Confident Ruby', author: 'Avdi Grimm' }] }
  8. it 'creates a new book' do
  9. action.call(params)
  10. book = repository.last
  11. expect(book.id).to_not be_nil
  12. expect(book.title).to eq(params.dig(:book, :title))
  13. end
  14. it 'redirects the user to the books listing' do
  15. response = action.call(params)
  16. expect(response[0]).to eq(302)
  17. expect(response[1]['Location']).to eq('/books')
  18. end
  19. end
  20. context 'with invalid params' do
  21. let(:params) { Hash[book: {}] }
  22. it 'returns HTTP client error' do
  23. response = action.call(params)
  24. expect(response[0]).to eq(422)
  25. end
  26. it 'dumps errors in params' do
  27. action.call(params)
  28. errors = action.params.errors
  29. expect(errors.dig(:book, :title)).to eq(['is missing'])
  30. expect(errors.dig(:book, :author)).to eq(['is missing'])
  31. end
  32. end
  33. end

Now our tests specify two alternative scenarios: our original happy path, and a new scenario in which validations fail. To make our tests pass, we need to implement validations.

Although you can add validation rules to the entity, Hanami also allows you to define validation rules as close to the source of the input as possible, i.e., the action. Hanami controller actions can use the params class method to define acceptable incoming parameters.

This approach both explicitly declares which params are allowed (others are discarded to prevent mass-assignment vulnerabilities from untrusted user input) and it adds rules to define which values are acceptable — in this case, we’ve specified that the nested attributes for a book’s title and author should be non-empty strings.

With our validations in place, we can limit our entity creation and redirection to cases where the incoming params are valid:

  1. # apps/web/controllers/books/create.rb
  2. module Web
  3. module Controllers
  4. module Books
  5. class Create
  6. include Web::Action
  7. expose :book
  8. params do
  9. required(:book).schema do
  10. required(:title).filled(:str?)
  11. required(:author).filled(:str?)
  12. end
  13. end
  14. def call(params)
  15. if params.valid?
  16. @book = BookRepository.new.create(params[:book])
  17. redirect_to '/books'
  18. else
  19. self.status = 422
  20. end
  21. end
  22. end
  23. end
  24. end
  25. end

When the params are valid, the Book is created, and the action redirects to a different URL. However, when the params are not valid, what happens?

First, the HTTP status code is set to 422 (Unprocessable Entity). Then the control will pass to the corresponding view, which needs to know which template to render. In this case, apps/web/templates/books/new.html.erb will be used to render the form again.

  1. # apps/web/views/books/create.rb
  2. module Web
  3. module Views
  4. module Books
  5. class Create
  6. include Web::View
  7. template 'books/new'
  8. end
  9. end
  10. end
  11. end

This approach will work nicely because Hanami’s form builder is smart enough to inspect the params in this action and populate the form fields with values found in the params. If the user fills in only one field before submitting, they are presented with their original input, saving them the frustration of typing it again.

Run your tests again and see they are all passing again!

Rather than just showing the user the same form they entered when something has gone wrong, we should give them a hint of what’s actually expected of them. Let’s adapt our form to show a notice about invalid field values.

First, we expect a list of errors to be included in the page when params contains errors:

  1. # spec/web/views/books/new_spec.rb
  2. RSpec.describe Web::Views::Books::New, type: :view do
  3. let(:params) { OpenStruct.new(valid?: false, error_messages: ['Title must be filled', 'Author must be filled']) }
  4. let(:exposures) { Hash[params: params] }
  5. let(:template) { Hanami::View::Template.new('apps/web/templates/books/new.html.erb') }
  6. let(:view) { described_class.new(template, exposures) }
  7. let(:rendered) { view.render }
  8. it 'displays list of errors when params contains errors' do
  9. expect(rendered).to include('There was a problem with your submission')
  10. expect(rendered).to include('Title must be filled')
  11. expect(rendered).to include('Author must be filled')
  12. end
  13. end

We should also update our feature spec to reflect this new behavior:

  1. # spec/web/features/add_book_spec.rb
  2. require 'features_helper'
  3. RSpec.describe 'Add a book' do
  4. # Spec written earlier omitted for brevity
  5. it 'displays list of errors when params contains errors' do
  6. visit '/books/new'
  7. within 'form#book-form' do
  8. click_button 'Create'
  9. end
  10. expect(current_path).to eq('/books')
  11. expect(page).to have_content('There was a problem with your submission')
  12. expect(page).to have_content('Title must be filled')
  13. expect(page).to have_content('Author must be filled')
  14. end
  15. end

We now have two failing tests, but that’s OK. It’s simple to fix them.

In our template, we can loop over params.error_messages (if there are any) and display a friendly message. Open up apps/web/templates/books/new.html.erb and update the top of the file, before the form_for call, to include this:

  1. # apps/web/templates/books/new.html.erb, at the top
  2. <h2>Add book</h2>
  3. <% unless params.valid? %>
  4. <div class="errors">
  5. <h3>There was a problem with your submission</h3>
  6. <ul>
  7. <% params.error_messages.each do |message| %>
  8. <li><%= message %></li>
  9. <% end %>
  10. </ul>
  11. </div>
  12. <% end %>
  13. <%#
  14. form_for :book, '/books' do
  15. ...
  16. end
  17. %>

Run your tests again and see they are all passing again!

  1. $ bundle exec rake
  2. ........
  3. Finished in 0.07811 seconds (files took 1.35 seconds to load)
  4. 18 examples, 0 failures

Improving Our Use Of The Router

The last improvement we are going to make is in the use of our router. Open up the routes file for the “web” application:

  1. # apps/web/config/routes.rb
  2. post '/books', to: 'books#create'
  3. get '/books/new', to: 'books#new'
  4. get '/books', to: 'books#index'
  5. root to: 'home#index'

Hanami provides a convenient helper method to build these REST-style routes that we can use to simplify our router a bit:

  1. root to: 'home#index'
  2. resources :books, only: [:index, :new, :create]

To get a sense of what routes are defined, now we’ve made this change, you can use the special command-line task routes to inspect the end result:

  1. $ bundle exec hanami routes
  2. Name Method Path Action
  3. root GET, HEAD / Web::Controllers::Home::Index
  4. books GET, HEAD /books Web::Controllers::Books::Index
  5. new_book GET, HEAD /books/new Web::Controllers::Books::New
  6. books POST /books Web::Controllers::Books::Create

The output for hanami routes shows you the name of the defined helper method (you can suffix this name with _path or _url and call it on the routes helper), the allowed HTTP method, the path and finally the controller action that will be used to handle the request.

Now we’ve applied the resources helper method; we can take advantage of the named route methods. Remember how we built our form using form_for?

  1. # apps/web/templates/books/new.html.erb
  2. <h2>Add book</h2>
  3. <%# ... %>
  4. <%=
  5. form_for :book, '/books' do
  6. # ...
  7. end
  8. %>

It’s silly to include a hard-coded path in our template when our router is already perfectly aware of which route to point the form to. We can use the routes helper method that is available in our views and actions to access route-specific helper methods:

  1. # apps/web/templates/books/new.html.erb
  2. <h2>Add book</h2>
  3. <%# ... %>
  4. <%=
  5. form_for :book, routes.books_path do
  6. # ...
  7. end
  8. %>

We can make a similar change in apps/web/controllers/books/create.rb:

  1. ...
  2. redirect_to routes.books_path
  3. ...

and in apps/web/templates/books/index.html.erb:

  1. ...
  2. ...

You could also extend this to the specs if you’d like, but changing the path can affect users so you may want to repeat yourself there (to make a potentially breaking change for users harder to implement).

Wrapping Up

Congratulations on completing your first Hanami project!

Let’s review what we’ve done: we’ve traced requests through Hanami’s major frameworks to understand how they relate to each other; we’ve seen how we can model our domain using entities and repositories; we’ve seen solutions for building forms, maintaining our database schema, and validating user input.

We’ve come a long way, but there’s still plenty more to explore. Explore the other guides, the , read the source code and follow the .

Above all, enjoy building amazing things!