Bird
Raised Fist0
Ruby on Railsframework~20 mins

Controller tests in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rails Controller Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Rails controller test?
Given the following test for a Rails controller action, what will be the test result?
Ruby on Rails
require 'rails_helper'

RSpec.describe ArticlesController, type: :controller do
  describe 'GET #show' do
    let(:article) { Article.create(title: 'Test', content: 'Content') }

    it 'returns a successful response' do
      get :show, params: { id: article.id }
      expect(response).to have_http_status(:success)
    end
  end
end
AThe test fails with a routing error because the route is missing.
BThe test fails because the article is not saved to the database.
CThe test passes because the show action returns HTTP status 200.
DThe test raises a syntax error due to missing end keywords.
Attempts:
2 left
💡 Hint
Check if the article is created and the show action is called correctly.
❓ state_output
intermediate
2:00remaining
What is the value of flash[:notice] after this controller test runs?
Consider this controller test snippet. What will be the value of flash[:notice] after the POST create action?
Ruby on Rails
RSpec.describe PostsController, type: :controller do
  describe 'POST #create' do
    it 'sets a flash notice on success' do
      post :create, params: { post: { title: 'Hello', body: 'World' } }
      # What is flash[:notice] here?
    end
  end
end

# Controller code:
# def create
#   @post = Post.new(post_params)
#   if @post.save
#     flash[:notice] = 'Post was successfully created.'
#     redirect_to @post
#   else
#     render :new
#   end
# end
A'Error creating post.'
B'Post was successfully created.'
Cnil
DRaises a NoMethodError
Attempts:
2 left
💡 Hint
The post is created with valid parameters, so the success branch runs.
🔧 Debug
advanced
2:00remaining
Why does this controller test raise an error?
This test raises an error when run. What is the cause?
Ruby on Rails
RSpec.describe UsersController, type: :controller do
  describe 'DELETE #destroy' do
    it 'deletes the user' do
      user = User.create(name: 'Alice')
      delete :destroy, params: { id: user.id }
      expect(User.find_by(id: user.id)).to be_nil
    end
  end
end

# Controller code:
# def destroy
#   User.find(params[:id]).destroy
#   redirect_to users_path
# end
AThe test raises ActiveRecord::RecordNotFound because User.find(user.id) fails after deletion.
BThe test raises a NoMethodError because destroy is undefined.
CThe test fails because the user is not created before the test.
DThe test raises a routing error due to missing route.
Attempts:
2 left
💡 Hint
Check what happens when you try to find a deleted record.
📝 Syntax
advanced
2:00remaining
Which option fixes the syntax error in this controller test?
Identify the correct syntax to test a PATCH update action in Rails controller tests.
Ruby on Rails
RSpec.describe CommentsController, type: :controller do
  describe 'PATCH #update' do
    let(:comment) { Comment.create(body: 'Old') }

    it 'updates the comment body' do
      patch :update, params: { id: comment.id, comment: { body: 'New' } }
      comment.reload
      expect(comment.body).to eq('New')
    end
  end
end
Apatch :update, params: { id: comment.id, comment: { body: 'New' } }
Bpatch update, params: { id: comment.id, comment: { body: 'New' } }
Cpatch :update, id: comment.id, comment: { body: 'New' }
Dpatch :update, { id: comment.id, comment: { body: 'New' } }
Attempts:
2 left
💡 Hint
The params hash must be passed with the key :params.
🧠 Conceptual
expert
2:00remaining
Which option best describes the purpose of controller tests in Rails?
Select the statement that most accurately explains why we write controller tests in Rails applications.
ATo test the database schema and ensure migrations run without errors.
BTo replace integration tests by testing all user flows in one place.
CTo check the styling and layout of views rendered by the controller.
DTo verify that controller actions respond correctly to HTTP requests and manipulate data as expected.
Attempts:
2 left
💡 Hint
Think about what controllers do in a Rails app and what tests should confirm.

Practice

(1/5)
1. What is the main purpose of a controller test in Rails?
easy
A. To check if web requests respond correctly and perform expected actions
B. To test database schema changes
C. To verify CSS styles are applied properly
D. To check JavaScript functions run without errors

Solution

  1. Step 1: Understand controller test role

    Controller tests simulate web requests to check if the controller responds correctly.
  2. Step 2: Compare options

    Only To check if web requests respond correctly and perform expected actions describes checking web requests and expected actions, which is the controller test's purpose.
  3. Final Answer:

    To check if web requests respond correctly and perform expected actions -> Option A
  4. Quick Check:

    Controller tests check web requests = A [OK]
Hint: Controller tests simulate web requests to check responses [OK]
Common Mistakes:
  • Confusing controller tests with database or view tests
  • Thinking controller tests check CSS or JavaScript
  • Assuming controller tests modify database schema
2. Which of the following is the correct syntax to simulate a GET request to the index action in a Rails controller test?
easy
A. get('/index')
B. get index
C. get index()
D. get :index

Solution

  1. Step 1: Recall Rails controller test syntax

    In Rails controller tests, the correct way to simulate a GET request is using get :action_name.
  2. Step 2: Analyze options

    get :index uses get :index, which is correct syntax. Others are invalid or incorrect Ruby syntax.
  3. Final Answer:

    get :index -> Option D
  4. Quick Check:

    Use symbol with get method = C [OK]
Hint: Use get :action_name with a symbol for controller tests [OK]
Common Mistakes:
  • Using string or method call syntax instead of symbol
  • Omitting colon before action name
  • Using parentheses incorrectly
3. Given this controller test snippet:
get :show, params: { id: 1 }
assert_response :success
assert_not_nil assigns(:user)

What does assert_not_nil assigns(:user) check?
medium
A. That the @user variable was assigned in the controller
B. That the user with id 1 exists in the database
C. That the response body contains the word 'user'
D. That the controller redirected to the user page

Solution

  1. Step 1: Understand assigns method in controller tests

    The assigns(:user) method accesses the instance variable @user set by the controller.
  2. Step 2: Interpret assert_not_nil usage

    assert_not_nil assigns(:user) checks that @user is not nil, meaning it was assigned.
  3. Final Answer:

    That the @user variable was assigned in the controller -> Option A
  4. Quick Check:

    assigns(:user) checks @user variable = B [OK]
Hint: assigns(:var) checks controller instance variable @var [OK]
Common Mistakes:
  • Thinking assigns checks database existence
  • Confusing assigns with response content
  • Assuming assigns checks redirects
4. Identify the error in this Rails controller test code:
post :create, user: { name: 'Alice' }
assert_redirected_to user_path(assigns(:user))
medium
A. assert_redirected_to should be assert_response
B. Using post instead of get for create action
C. Missing params: keyword before user hash in post request
D. assigns(:user) cannot be used in controller tests

Solution

  1. Step 1: Check syntax for post request with parameters

    In Rails 5+, parameters must be wrapped inside params: keyword.
  2. Step 2: Analyze given code

    The code uses post :create, user: { name: 'Alice' } missing params:, causing syntax error.
  3. Final Answer:

    Missing params: keyword before user hash in post request -> Option C
  4. Quick Check:

    Use params: for parameters in post requests = A [OK]
Hint: Always use params: keyword for request parameters [OK]
Common Mistakes:
  • Omitting params: keyword in request methods
  • Confusing HTTP verbs for actions
  • Misusing assertion methods
5. You want to test that after creating a new user, the controller redirects to the user's show page and sets a flash notice. Which test code correctly checks both behaviors?
hard
A. post :create, params: { user: { name: 'Bob' } } assert_response :redirect assert_nil flash[:notice]
B. post :create, params: { user: { name: 'Bob' } } assert_redirected_to user_path(assigns(:user)) assert_equal 'User created!', flash[:notice]
C. get :create, params: { user: { name: 'Bob' } } assert_redirected_to user_path(assigns(:user)) assert flash[:alert] == 'User created!'
D. post :create, user: { name: 'Bob' } assert_response :success assert flash[:notice] == 'User created!'

Solution

  1. Step 1: Check HTTP verb and parameters

    Creating a user uses POST with params: keyword, so post :create, params: { user: { name: 'Bob' } } assert_redirected_to user_path(assigns(:user)) assert_equal 'User created!', flash[:notice] is correct here.
  2. Step 2: Verify assertions for redirect and flash

    post :create, params: { user: { name: 'Bob' } } assert_redirected_to user_path(assigns(:user)) assert_equal 'User created!', flash[:notice] asserts redirect to user's show page and flash notice equals 'User created!'. This matches the requirement.
  3. Step 3: Eliminate incorrect options

    post :create, user: { name: 'Bob' } assert_response :success assert flash[:notice] == 'User created!' misses params: keyword and uses assert_response :success instead of redirect. get :create, params: { user: { name: 'Bob' } } assert_redirected_to user_path(assigns(:user)) assert flash[:alert] == 'User created!' uses GET instead of POST and wrong flash key. post :create, params: { user: { name: 'Bob' } } assert_response :redirect assert_nil flash[:notice] asserts flash[:notice] is nil, which is wrong.
  4. Final Answer:

    post :create, params: { user: { name: 'Bob' } } assert_redirected_to user_path(assigns(:user)) assert_equal 'User created!', flash[:notice] -> Option B
  5. Quick Check:

    POST with params, redirect, and flash notice = D [OK]
Hint: Use post with params:, assert_redirected_to, and assert_equal flash [OK]
Common Mistakes:
  • Using get instead of post for create action
  • Forgetting params: keyword
  • Checking wrong flash key or missing redirect assertion
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard