Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

flash[:error] = "Message" returns nil even when defined

I am on Creating the Friendship Controller and my controller is returning nil on the new defined method even though I set it to respond?

test/functional/user_friendships_controller_test.rb

require 'test_helper'

class UserFriendshipsControllerTest < ActionController::TestCase
  context "#new" do
    context "when not logged in" do
      should "redirect to the login page" do
        get :new
        assert_response :redirect
      end
    end

    context "when logged in" do
        setup do
            sign_in users(:arthur)
        end

        should "get new and return success" do
            get :new
            assert_response :success
        end
    end

    should "should set a flash error if the friend_id params are missing" do
        get :new, {}
        assert_equal "Friend required", flash[:error]
    end

  end
end

app/controllers/user_friendships_controller.rb

class UserFriendshipsController < ApplicationController
    before_filter :authenticate_user!, only: [:new]

    def new
        unless params[:friend_id]
          flash[:error] = "Friend required"
        end
    end
end

Terminal Test Failure

drive:/>ruby -I test test/functional/user_friendships_controller_test.rb
Run options:

# Running tests:

F..

Finished tests in 0.134008s, 22.3867 tests/s, 22.3867 assertions/s.

  1) Failure:
test: #new should should set a flash error if the friend_id params are missing.
(UserFriendshipsControllerTest) [test/functional/user_friendships_controller_tes
t.rb:25]:
<"Friend required"> expected but was
<nil>.

3 tests, 3 assertions, 1 failures, 0 errors, 0 skips

2 Answers

You are not inside the context "When logged in" Look at your "ends". That test needs to be inside context "when logged in" do. So should look like this:

context "when logged in" do
    setup do
        sign_in users(:arthur)
    end

    should "get new and return success" do
        get :new
        assert_response :success
    end

should "should set a flash error if the friend_id params are missing" do
    get :new, {}
    assert_equal "Friend required", flash[:error]
end
end

Thank you