Ruby on rails 错误配置的Rails模型关联导致测试失败
我已经学习过Michael Hartl的rails教程好几次了,现在我正在使用它作为基础来创建我自己的应用程序。用户将是大学的员工,大部分数据将由大学在视图中呈现,而不仅仅由用户呈现。出于这个原因,我创建了一个大学模型,在universions表中植入了一些大学名称,在新用户表单中使用collection\u select允许用户选择他们的大学,并在我的Users表中添加了一列University\u id。我配置的关联是,用户属于university,university有很多用户。(在我想象的用例中,一所大学将有多个用户,他们可以登录并查看他们的个人数据,也可以查看整个大学的数据) 注册表单似乎可以根据需要运行,允许用户选择他们的大学、注册并保存到模型中 问题是,我在教程中构建的测试套件现在抛出了多个错误,我在几个小时的修改后无法解决这些错误。当我注释掉时,错误就解决了 所属:大学 从models/user.rbRuby on rails 错误配置的Rails模型关联导致测试失败,ruby-on-rails,has-many,belongs-to,Ruby On Rails,Has Many,Belongs To,我已经学习过Michael Hartl的rails教程好几次了,现在我正在使用它作为基础来创建我自己的应用程序。用户将是大学的员工,大部分数据将由大学在视图中呈现,而不仅仅由用户呈现。出于这个原因,我创建了一个大学模型,在universions表中植入了一些大学名称,在新用户表单中使用collection\u select允许用户选择他们的大学,并在我的Users表中添加了一列University\u id。我配置的关联是,用户属于university,university有很多用户。(在我想象
class User < ApplicationRecord
has_many :referral_requests
belongs_to :university
attr_accessor :remember_token, :activation_token, :reset_token
before_save :downcase_email
before_create :create_activation_digest
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :university_id, presence: true
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# Returns a random token.
def User.new_token
SecureRandom.urlsafe_base64
end
# Remembers a user in the database for use in persistent sessions.
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
# Returns true if the given token matches the digest.
def authenticated?(remember_token)
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
# Forgets a user.
def forget
update_attribute(:remember_digest, nil)
end
# Returns true if the given token matches the digest.
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
# Activates an account.
def activate
update_attribute(:activated, true)
update_attribute(:activated_at, Time.zone.now)
end
# Sends activation email.
def send_activation_email
UserMailer.account_activation(self).deliver_now
end
# Sets the password reset attributes.
def create_reset_digest
self.reset_token = User.new_token
update_attribute(:reset_digest, User.digest(reset_token))
update_attribute(:reset_sent_at, Time.zone.now)
end
# Sends password reset email.
def send_password_reset_email
UserMailer.password_reset(self).deliver_now
end
# Returns true if a password reset has expired.
def password_reset_expired?
reset_sent_at < 2.hours.ago
end
def feed
ReferralRequest.where("user_id = ?", id)
end
private
# Converts email to all lower-case.
def downcase_email
self.email = email.downcase
end
# Creates and assigns the activation token and digest.
def create_activation_digest
self.activation_token = User.new_token
self.activation_digest = User.digest(activation_token)
end
end
我做错了什么?任何和所有的反馈,让我摆脱困境,继续前进,将不胜感激
Rails 5.0.1
测试失败:
FAIL["test_password_resets", PasswordResetsTest, 1.204568000001018]
test_password_resets#PasswordResetsTest (1.20s)
Expected false to be truthy.
test/integration/password_resets_test.rb:58:in `block in <class:PasswordResetsTest>'
/Users/MichaelBaker/.rvm/gems/ruby-2.4.0/gems/will_paginate-3.1.5/lib/will_paginate/view_helpers/link_renderer.rb:27: warning: constant ::Fixnum is deprecated ] 48% Time: 00:00:01, ETA: 00:00:02
/Users/MichaelBaker/.rvm/gems/ruby-2.4.0/gems/will_paginate-3.1.5/lib/will_paginate/view_helpers/link_renderer.rb:91: warning: constant ::Fixnum is deprecated
FAIL["test_valid_signup_information_with_account_activation", UsersSignupTest, 2.8807119999983115]
test_valid_signup_information_with_account_activation#UsersSignupTest (2.88s)
"User.count" didn't change by 1.
Expected: 35
Actual: 34
test/integration/users_signup_test.rb:25:in `block in <class:UsersSignupTest>'
FAIL["test_successful_edit", UsersEditTest, 3.048766000007163]
test_successful_edit#UsersEditTest (3.05s)
Expected true to be nil or false
test/integration/users_edit_test.rb:31:in `block in <class:UsersEditTest>'
FAIL["test_successful_edit_with_friendly_forwarding", UsersEditTest, 3.1065749999979744]
test_successful_edit_with_friendly_forwarding#UsersEditTest (3.11s)
Expected response to be a <3XX: redirect>, but was a <200: OK>
test/integration/users_edit_test.rb:49:in `block in <class:UsersEditTest>'
FAIL["test_should_be_valid", UserTest, 3.363870000001043]
test_should_be_valid#UserTest (3.36s)
Expected false to be truthy.
test/models/user_test.rb:11:in `block in <class:UserTest>'
routes.rb
Rails.application.routes.draw do
post 'universities/create'
get 'password_resets/new'
get 'password_resets/edit'
root 'static_pages#home'
get '/help', to: 'static_pages#help'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
get '/signup', to: 'users#new'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
resources :users
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :referral_requests, only: [:index, :new, :create, :show, :edit, :update, :destroy]
end
我需要修改config/initializers中的new_framework_defaults.rb,并将以下语句从true更改为false:
Rails.application.config.active_record.belongs_to_required_by_default = false
class User < ApplicationRecord
has_many :referral_requests
belongs_to :university
attr_accessor :remember_token, :activation_token, :reset_token
before_save :downcase_email
before_create :create_activation_digest
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :university_id, presence: true
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# Returns a random token.
def User.new_token
SecureRandom.urlsafe_base64
end
# Remembers a user in the database for use in persistent sessions.
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
# Returns true if the given token matches the digest.
def authenticated?(remember_token)
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
# Forgets a user.
def forget
update_attribute(:remember_digest, nil)
end
# Returns true if the given token matches the digest.
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
# Activates an account.
def activate
update_attribute(:activated, true)
update_attribute(:activated_at, Time.zone.now)
end
# Sends activation email.
def send_activation_email
UserMailer.account_activation(self).deliver_now
end
# Sets the password reset attributes.
def create_reset_digest
self.reset_token = User.new_token
update_attribute(:reset_digest, User.digest(reset_token))
update_attribute(:reset_sent_at, Time.zone.now)
end
# Sends password reset email.
def send_password_reset_email
UserMailer.password_reset(self).deliver_now
end
# Returns true if a password reset has expired.
def password_reset_expired?
reset_sent_at < 2.hours.ago
end
def feed
ReferralRequest.where("user_id = ?", id)
end
private
# Converts email to all lower-case.
def downcase_email
self.email = email.downcase
end
# Creates and assigns the activation token and digest.
def create_activation_digest
self.activation_token = User.new_token
self.activation_digest = User.digest(activation_token)
end
end
class University < ApplicationRecord
has_many :users
end
<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :email %>
<%= f.email_field :email, class: 'form-control' %>
<%= f.label :university%>
<%= collection_select( :user, :university_id, University.all, :id, :name, prompt: true) %>
<%= f.label :password %>
<%= f.password_field :password, class: 'form-control' %>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation, class: 'form-control' %>
<%= f.submit "Create my account", class: "btn btn-primary" %>
<% end %>
</div>
</div>
class UsersController < ApplicationController
before_action :logged_in_user, only: [:show, :index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def index
@users = User.paginate(page: params[:page])
end
def show
@user = User.find(params[:id])
@referral_requests = @user.referral_requests.paginate(page: params[:page])
end
def new
@user = User.new
end
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
def edit
end
def update
if @user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to @user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User deleted"
redirect_to users_url
end
private
def user_params
params.require(:user).permit(:name, :email, :university_id, :password, :password_confirmation)
end
# Before filters
# Confirms the correct user.
def correct_user
@user = User.find(params[:id])
redirect_to(root_url) unless current_user?(@user)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
class UniversitiesController < ApplicationController
end
ActiveRecord::Schema.define(version: 20170622190254) do
create_table "referral_requests", force: :cascade do |t|
t.text "content"
t.string "gender"
t.string "preferred_gender"
t.string "insurance"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id", "created_at"], name: "index_referral_requests_on_user_id_and_created_at"
t.index ["user_id"], name: "index_referral_requests_on_user_id"
end
create_table "universities", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.string "remember_digest"
t.boolean "admin", default: false
t.string "activation_digest"
t.boolean "activated", default: false
t.datetime "activated_at"
t.string "reset_digest"
t.datetime "reset_sent_at"
t.integer "university_id"
t.index ["email"], name: "index_users_on_email", unique: true
end
end
Rails.application.routes.draw do
post 'universities/create'
get 'password_resets/new'
get 'password_resets/edit'
root 'static_pages#home'
get '/help', to: 'static_pages#help'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
get '/signup', to: 'users#new'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
resources :users
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :referral_requests, only: [:index, :new, :create, :show, :edit, :update, :destroy]
end
Rails.application.config.active_record.belongs_to_required_by_default = false