Forms are Simple

All the code is refactored and shiny. The tests look nice and we have the beginnings of a framework but we’ve only completed one story. Let’s work on the next one.

  • An author can publish a blog post.

I’ve been using (and loving!) the simple_form gem for a while now. It’s one of the things that I miss most about moving to React. Let’s see how hard it is to reproduce some of that functionality here. There are a lot of moving parts.

We’ll do the rails bit first because it is easy.

  test 'create a blog post' do
    post posts_url(format: :json), params: {
        post: {
            title: 'A new day',
            body: 'First post!'
    assert_response :success
    json = JSON.parse response.body, symbolize_names: true

    # The post was created
    @post = Post.last
    assert_equal 'A new day', @post.title

    # Return the post as JSON
    assert_equal, json[:id]
    assert_equal 'A new day', json[:title]
class PostsController < ApplicationController
  def create
    @post = post_params
      render :show
      render json: @post.errors, status: :unprocessable_entity

Now we need a form in React to submit a post.

class PostTest < ActiveSupport::TestCase
  test 'post has a title and a body'
  test 'validate the title and body'
  test 'trim the title and body'

We’ll use the strip_attributes gem to trim the fields.

# Gemfile 
gem 'strip_attributes'
bundle install
class Post < ApplicationRecord
  validates :title, length: { minimum: 2, maximum: 255}
  validates :body,  length: { minimum: 2}

We’ll work on the client side tomorrow.

Published by


I've been coding professionally for 30 years, 25 of those in Silicon Valley. I'm home now in beautiful Bristol, England.

Leave a Reply

Your email address will not be published. Required fields are marked *