Using BDD to Implement Radio Buttons in Rails
This guide will focus on how to implement radio buttons in a Rails form and how we can leverage Capybara to build the feature.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

This guide will focus on how to implement radio buttons in a Rails form and how we can leverage Capybara to build the feature.

To implement radio buttons to edit our status element, let's first create a file called approval_workflow_spec.rb in spec/features. Though we can put these tests in our other integration test files, I feel it's best to have a separate one dedicated for our workflow. We are naming files that end with the word spec because rspec will detect these files and automatically run any tests or scripts inside them.

Let's start with creating a describe block called navigate. Since we know that a user will have to be logged in to perform this action, the first thing we'll do is create an AdminUser and log them in.

# spec/features/approval_workflow_spec.rb

describe 'navigate' do
  before do
    @admin_user = FactoryGirl.create(:admin_user)
    login_as(@admin_user, :scope => :user)
  end

In the next test block we are going to create a block that contains our specs related to editing. We'll create a post in the before block. Next, we'll have a test case that visits the edit page of the post. Then, we'll check the radio button and press save. Lastly we'll create an expectation to see if the the status is equal to approved.

# spec/features/approval_workflow_spec.rb

describe 'edit' do
  before do
    @post = FactoryGirl.create(:post)
  end

  it 'has a status that can be edited on the form' do
    visit edit_post_path(@post)

    choose('post_status_approved')
    click_on "Save"

    expect(@post.reload.status).to eq('approved')
  end
end

If you run rspec you'll see that it throws an error, however it's not explicit. So let's start the server and test this in the browser. When you edit a post and save it, there's no error but the status field doesn't get updated either. If you go back to the console, it reveals that our transaction has an error:

Unpermitted parameter : status

Now, do you remember how we added date and rationale as required parameters in our post_controller.rb file? We have to include status as well. With this in mind let's update the post_controller.rb to include:

# app/controllers/posts_controller.rb

private

  def post_params
    params.require(:post).permit(:date, :rationale, :status)
  end

Now, if you test it in the browser, it works! If you run rspec you'll see that the tests are all now passing.

Resources