Adding a Button to Create Posts in Rails
In this guide we are going to add a tab that'll allow users to create a new post.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this guide we are going to add a tab in our navigation bar that'll allow users to create a new post.

As always, let's start with our test case. Open the post_spec.rb in the features folder, and add this code:

# spec/features/post_spec.rb

describe 'new' do
  it 'has a link from the homepage' do
    visit root_path

    click_link("new_post_from_nav")
    expect(page.status_code).to eq(200)
  end
end

Here, we are asking the test to visit the root_path, click a link, and expect to see a page. If you run rspec, it'll obviously fail because we don't have some things in place.

To fix it, open our `_nav.html.erb' partial and update it to match this code:

<!-- app/views/shared/_nav.html.erb -->

<div class='logo'>
  <h1>Time Tracker</h1>
</div>

<ul class="custom-nav nav nav-tabs">
  <li class="<%= active?(root_path) %>">
    <%= link_to "Home", root_path %>
  </li>
  <li class="<%= active?(posts_path) %>">
    <%= link_to "Time Entries", posts_path %>
  </li>
  <li class="<%= active?(new_post_path) %>">
    <%= link_to "Add New Entry", new_post_path, id: 'new_post_from_nav' %>
  </li>

If you see, we are creating a link to new_post_path and passing an HTML ID to it. This ID is the same as the one we passed in our test case.

Now, all of our tests should be green.

Let's see it in the browser now.

medium

That should be all that we need for this feature.

Resources