Friendly_id gem及其对测试的影响(无slug)

时间:2015-05-26 21:41:37

标签: ruby-on-rails ruby ruby-on-rails-4 testing friendly-id

我通过添加到User模型实现了friendly_id gem:

include FriendlyId
friendly_id :username

在控制器中,我添加了User.find(params[:id])替换为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

所以我没有使用Slug。

问题:现在突然间各种测试都失败了。下面是一个例子。我按照建议添加了.to_param,但这并未改变错误消息:

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

此测试使用以下测试助手:

  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

错误消息:

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>'

这与friendly_id宝石有什么关系?我真的不明白它,也不知道我需要对我的测试做出哪些调整。

1 个答案:

答案 0 :(得分:1)

抱歉,我最初误解了您的问题并且没有意识到您已将控制器更改为使用User.friendly.find - 这是不寻常的,因为通常您希望将友好ID用于这些类型的网址。

因此,因为您仍在使用原始id,所以您需要在测试中提供,即。你需要把:

get user_path(@admin.id)

如果您只是提供@admin,则Rails会在其上调用.to_param,这将是友好ID,如果您这样做,我会找到:User.find(params[:id])不会现在您已转换为User.friendly.find(params[:id])