Wait a minute! It’s a post, man.

We’ll start with the Post model first.

I’ll keep the commentary to a minimum because you know this stuff already.

rails generate model Post title:string body:text
rails db:migrate

We’ll need a test framework. I like Minitest.

# Gemfile 
gem 'minitest', group: :test
bundle install

I use TDD but you can do whatever you like. I’m not your dad.

I’ll fast-forward though the details.

require 'test_helper'
class PostTest < ActiveSupport::TestCase
  test 'a post has a title and a body' do
    post = Post.create! title: 'The title', body: 'The body.'
    assert_equal 'The title', post.title
    assert_equal 'The body.', post.body
  end
end
rails test

.E

Error:
PostsControllerTest#test_should_get_index:
NameError: undefined local variable or method `posts_index_url' for #<PostsControllerTest:0x00007f8939850650>
    test/controllers/posts_controller_test.rb:5:in `block in <class:PostsControllerTest>'

PostTest passes already but PostControllerTest is failing because the path is wrong. Let’s fix that.

require 'test_helper'
class PostsControllerTest < ActionDispatch::IntegrationTest
  test 'should get index' do
    get posts_url
    assert_response :success
  end
end
rails test

# Running:

..

Finished in 0.382970s, 5.2223 runs/s, 7.8335 assertions/s.
2 runs, 3 assertions, 0 failures, 0 errors, 0 skips

Our React app is going to need some JSON. Let’s add a show action to PostsController.

require 'test_helper'
class PostsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @post = Post.create! title: 'The title', body: 'The body.'
  end

  test 'fetch a post as json' do
    get post_url(@post, format: :json)
    assert_response :success

    json = JSON.parse response.body, symbolize_names: true
    assert_equal @post.id, json[:id]
    assert_equal 'The title', json[:title]
    assert_equal 'The body.', json[:body]
  end
end
# PostsController.rb
class PostsController < ApplicationController
  before_action :set_post, only: :show
  
  private
  def set_post
    @post = Post.find params[:id]
  end
end

# views/posts/show.json.jbuilder
json.extract! @post, :id, :title, :body, :created_at, :updated_at

Let’s create a post so we can see what the JSON looks like.

# In the rails console
Post.create! title: 'React on Rails', body: 'I can use React with Rails.'
open http://localhost:3000/posts/1.json

That’s the back-end taken care of. We’ll build a React component to show our post 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 *