Nick
Nick

Reputation: 3090

Friendly_id gem and its effects on tests (without slug)

I've implemented friendly_id gem by adding to the User model:

include FriendlyId
friendly_id :username

In the controller I've added replaced User.find(params[:id]) with User.friendly.find(params[:id]):

  def show
    @user = User.friendly.find(params[:id])           # Line 21
    redirect_to signup_url and return unless (@user.activated)
  end

So I'm not using Slug.

Problem: Now suddenly all sorts of tests fail. One example below. I added .to_param as suggested but this didn't change the error message:

class AvatarUploadTest < ActionDispatch::IntegrationTest
  def setup
    @admin             = users(:michael)
  end

  test "avatar upload" do
    log_in_as("user", @admin.to_param)    # Helper method that logs in.
    get user_path(@admin)                 # Line 16
    ...etc

This test uses the following test helper:

  def log_in_as(type, user, options = {})
    password    = options[:password]    || 'password'
    remember_me = options[:remember_me] || '1'
    if integration_test?
      post login_path, session: { email:       user.email,
                                  password:    password,
                                  remember_me: remember_me }
    else
      if type == "user"
        session[:user_id] = user.id
      elsif type == "member"
        session[:member_id] = user.id
      end
    end
  end

The error message:

ERROR["test_avatar_upload", AvatarUploadTest, 2015-04-14 13:46:57 +0000]
 test_avatar_upload#AvatarUploadTest (1429019217.17s)
ActiveRecord::RecordNotFound:         ActiveRecord::RecordNotFound: ActiveRecord::RecordNotFound
            app/controllers/users_controller.rb:21:in `show'
            test/integration/avatar_upload_test.rb:16:in `block in <class:AvatarUploadTest>'
        app/controllers/users_controller.rb:21:in `show'
        test/integration/avatar_upload_test.rb:16:in `block in <class:AvatarUploadTest>'

How does this relate to the friendly_id gem? I don't really understand it and don't know what adjustments I need to make to my tests.

Upvotes: 2

Views: 831

Answers (1)

smathy
smathy

Reputation: 27961

Sorry, I misread your question at first and hadn't realized that you had changed your controller to use User.friendly.find - this is unusual because usually you want to use the friendly id for these sorts of URLs.

So, because you're still using the raw id then you need to supply that in your test, ie. you need to put:

get user_path(@admin.id)

If you just provide @admin then Rails will call .to_param on it, which will be the friendly ID, which would be found if you did: User.find(params[:id]) but will not be found now that you've converted to User.friendly.find(params[:id])

Upvotes: 2

Related Questions