【发布时间】:2019-03-25 04:12:18
【问题描述】:
我正在尝试让测试适用于注册和帐户激活。模板中似乎有一个错误,它试图使用一种方法创建一个路由。这是错误:
ERROR["test_valid_signup_information_with_account_activation", UsersSignupTest, 1.614055]
test_valid_signup_information_with_account_activation#UsersSignupTest (1.61s)
ActionView::Template::Error: ActionView::Template::Error: No route matches {:action=>"edit", :controller=>"account_activations", :email=>"user@example.com", :format=>nil, :id=>nil} missing required keys: [:id]
模板创建路由:
<%= link_to "Activate", edit_account_activation_url(@user.activation_token,
email: @user.email) %>
我在路由中使用资源,所以你会认为这会产生正确的路由。这是我的路线文件:
Rails.application.routes.draw do
root 'static_pages#home'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
resources :users
resources :account_activations, only: [:edit]
end
错误说它缺少一个 id,这对我来说意味着它需要在访问路由之前将记录插入数据库(并因此生成一个 id)。但是在 @user.send_activation_email
行保存后出现错误class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def create
@user = User.new(user_params)
if @user.save
@user.send_activation_email
flash[:info] = "Please check your email to activate your account."
redirect_to root_url
else
render 'new'
end
end
使用定义 send_activation_email 方法的用户类:
class User < ActiveRecord::Base
attr_accessor :remember_token, :activation_token
before_save :downcase_email
before_create :create_activation_digest
# Sends activation email.
def send_activation_email
UserMailer.account_activation(self).deliver_now
end
最后,帐户激活控制器确实具有编辑功能,因此应用程序应该可以找到路由。在书中,编辑功能尚未实现,它仍然可以工作......我还是继续实现了编辑功能:
class AccountActivationsController < ApplicationController
def edit
user = User.find_by(email: params[:email])
if user && !user.activated? && user.authenticated?(:activation, params[:id])
user.update_attribute(:activated, true)
user.update_attribute(:activated_at, Time.zone.now)
log_in user
flash[:success] = "Account activated!"
redirect_to user
else
flash[:danger] = "Invalid activation link"
redirect_to root_url
end
end
end
所以我想问题是,为什么没有生成这个 id?
最后是产生错误的测试:
test "valid signup information" do
get signup_path
assert_difference 'User.count', 1 do
post_via_redirect users_path, user: { name: "Example User",
email: "user@example.com",
password: "password",
password_confirmation: "password" }
end
# assert_template 'users/show'
# assert is_logged_in?
end
【问题讨论】:
-
听起来activation_token是nil。
-
我也有同样的问题,你能解决吗?同样在我的情况下,edit_account_activation[s]_url 正在工作,请注意 s,没有编译器说没有这样的方法
标签: ruby-on-rails