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 @post.id, json[:id]
    assert_equal 'A new day', json[:title]
  end
class PostsController < ApplicationController
  def create
    @post = Post.new post_params
    if @post.save
      render :show
    else
      render json: @post.errors, status: :unprocessable_entity
    end
  end
...

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'
end

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

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

We’ll work on the client side tomorrow.

Published by

Kevin

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 *