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 so far.
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. It’s one of the things from Rails that I miss most after switching to React.
Let’s see if we can reproduce some of that functionality here. There are a lot of moving parts.
We’ll do the rails bit first because it is easy.
# posts_controller_test.rb 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, status: :created, location: @post else render json: @post.errors, status: :unprocessable_entity end end # ... existing stuff def post_params params.require(:post).permit(:title, :body) end end
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.