0
0
Ruby on Railsframework~30 mins

Controller tests in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Basic Controller Tests in Rails
📖 Scenario: You are building a simple blog application in Rails. You want to make sure your PostsController works correctly by writing tests for its main actions.
🎯 Goal: Write controller tests for the PostsController to check that the index and show actions respond successfully and render the correct templates.
📋 What You'll Learn
Create a test file for PostsController in test/controllers/posts_controller_test.rb
Write a test for the index action that checks for a successful HTTP response
Write a test for the show action that checks for a successful HTTP response
Use Rails built-in test framework syntax
💡 Why This Matters
🌍 Real World
Controller tests help ensure that your web app's pages load correctly and respond as expected before you deploy your app.
💼 Career
Writing controller tests is a common task for Rails developers to maintain code quality and prevent bugs in web applications.
Progress0 / 4 steps
1
Setup test data
Create a Post record in the test database with title set to 'Test Post' and body set to 'This is a test post.'. Write this inside the setup method of PostsControllerTest.
Ruby on Rails
Need a hint?

Use Post.create inside the setup method to create the test post.

2
Test the index action response
Add a test method called test_index_should_get_success that sends a get request to posts_url and asserts the response is successful using assert_response :success.
Ruby on Rails
Need a hint?

Use get posts_url and then assert_response :success inside the test method.

3
Test the show action response
Add a test method called test_show_should_get_success that sends a get request to post_url(@post) and asserts the response is successful using assert_response :success.
Ruby on Rails
Need a hint?

Use get post_url(@post) and assert_response :success inside the test method.

4
Complete the test file
Ensure the test file test/controllers/posts_controller_test.rb includes the setup method and both test methods test_index_should_get_success and test_show_should_get_success inside the PostsControllerTest class.
Ruby on Rails
Need a hint?

Make sure the class and methods are properly closed with end.