2017-06-22 61 views
0

我已经经历了迈克尔·哈特尔的轨工作教程几次,我现在使用它作为一个基地,以创建自己的应用程序。用户要成为大学的员工和许多数据将在意见的大学,而不是简单地由用户呈现。出于这个原因,我创建了一个大学的模式,在大学表播种一些大学的名字,在新的用户形式使用collection_select允许用户选择自己的大学,并添加一列university_id到我的用户表。我配置的关联是用户属于大学,大学有很多用户。 (在使用情况下,我想象,一个给定的大学会有谁可以登录并查看他们的个人数据,而且全校范围内的数据的多个用户)导致测试失败配置错误Rails的模型关联

的注册表格似乎需要的功能,允许用户选择他们的大学,注册并保存到模型中。

的问题是,测试套件我建在教程现在抛出,我不能摆弄了几个小时后,解决多个错误。大学 从型号/ user.rb

我在做什么错了:错误,当我注释掉 belongs_to的解决?任何和所有的反馈,让我再次移动,将不胜感激。

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

测试/模型/ user_test.rb

require 'test_helper' 

class UserTest < ActiveSupport::TestCase 

     def setup 
     @user = User.new(name: "Example User", email: "[email protected]", university_id: 1 , 
      password: "foobar", password_confirmation: "foobar") 
     end 

    test "should be valid" do 
    assert @user.valid? 
    end 

test "name should be present" do 
    @user.name = "  " 
    assert_not @user.valid? 
    end 

    test "email should be present" do 
    @user.email = "  " 
    assert_not @user.valid? 
    end 

test "name should not be too long" do 
    @user.name = "a" * 51 
    assert_not @user.valid? 
    end 

    test "email addresses should be unique" do 
    duplicate_user = @user.dup 
    duplicate_user.email = @user.email.upcase 
    @user.save 
    assert_not duplicate_user.valid? 
    end 

    test "email should not be too long" do 
    @user.email = "a" * 244 + "@example.com" 
    assert_not @user.valid? 
    end 

    test "email validation should reject invalid addresses" do 
    invalid_addresses = %w[[email protected],com user_at_foo.org [email protected] 
          [email protected]_baz.com [email protected]+baz.com [email protected]] 
    invalid_addresses.each do |invalid_address| 
     @user.email = invalid_address 
     assert_not @user.valid?, "#{invalid_address.inspect} should be invalid" 
    end 
    end 
    test "password should be present (nonblank)" do 
    @user.password = @user.password_confirmation = " " * 6 
    assert_not @user.valid? 
    end 

    test "password should have a minimum length" do 
    @user.password = @user.password_confirmation = "a" * 5 
    assert_not @user.valid? 
    end 

    test "authenticated? should return false for a user with nil digest" do 
    assert_not @user.authenticated?(:remember, '') 
    end 
end 

测试/集成/ users_edit_test.rb

require 'test_helper' 

class UsersEditTest < ActionDispatch::IntegrationTest 

    def setup 
    @user = users(:michael) 
    end 

    test "unsuccessful edit" do 
    log_in_as(@user) 
    get edit_user_path(@user) 
    assert_template 'users/edit' 
    patch user_path(@user), params: { user: { name: "", 
               email: "[email protected]", 
               password:    "foo", 
               password_confirmation: "bar" } } 

    assert_template 'users/edit' 
    end 

test "successful edit" do 
    log_in_as(@user) 
    get edit_user_path(@user) 
    assert_template 'users/edit' 
    name = "Foo Bar" 
    email = "[email protected]" 
    patch user_path(@user), params: { user: { name: name, 
               email: email, 
               password:    "", 
               password_confirmation: "" } } 
    assert_not flash.empty? 
    assert_redirected_to @user 
    @user.reload 
    assert_equal name, @user.name 
    assert_equal email, @user.email 
    end 

    test "successful edit with friendly forwarding" do 
    get edit_user_path(@user) 
    log_in_as(@user) 
    assert_redirected_to edit_user_url(@user) 
    name = "Foo Bar" 
    email = "[email protected]" 
    patch user_path(@user), params: { user: { name: name, 
               email: email, 
               password:    "", 
               password_confirmation: "" } } 
    assert_not flash.empty? 
    assert_redirected_to @user 
    @user.reload 
    assert_equal name, @user.name 
    assert_equal email, @user.email 
    end 
end 

测试/集成/用户_signup_test.rb

require 'test_helper' 

class UsersSignupTest < ActionDispatch::IntegrationTest 

    def setup 
    ActionMailer::Base.deliveries.clear 
    end 

    test "invalid signup information" do 
    get signup_path 
    assert_no_difference 'User.count' do 
     post users_path, params: { user: { name: "", 
             email: "[email protected]", 
             university_id: 1 , 
             password:    "foo", 
             password_confirmation: "bar" } } 
    end 
    assert_template 'users/new' 
    assert_select 'div#error_explanation' 
    assert_select 'div.field_with_errors' 
    end 

    test "valid signup information with account activation" do 
    get signup_path 
    assert_difference 'User.count', 1 do 
     post users_path, params: { user: { name: "Example User", 
             email: "[email protected]", 
             university_id: 1 , 
             password:    "password", 
             password_confirmation: "password" } } 
    end 
    assert_equal 1, ActionMailer::Base.deliveries.size 
    user = assigns(:user) 
    assert_not user.activated? 
    # Try to log in before activation. 
    log_in_as(user) 
    assert_not is_logged_in? 
    # Invalid activation token 
    get edit_account_activation_path("invalid token", email: user.email) 
    assert_not is_logged_in? 
    # Valid token, wrong email 
    get edit_account_activation_path(user.activation_token, email: 'wrong') 
    assert_not is_logged_in? 
    # Valid activation token 
    get edit_account_activation_path(user.activation_token, email: user.email) 
    assert user.reload.activated? 
    follow_redirect! 
    assert_template 'users/show' 
    assert is_logged_in? 
    end 
end 

模型/ user.rb

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+\-.][email protected][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 

模型/ university.rb

class University < ApplicationRecord 
    has_many :users 
end 

用户/ new.html.erb

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

控制器/ users_controller.rb

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 

控制器/ universities_controller.rb

class UniversitiesController < ApplicationController 
end 

schema.rb

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 

的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 

回答

0

我需要修改new_framework_defaults.rb在配置/初始化并将以下语句从true更改为false :

Rails.application.config.active_record.belongs_to_required_by_default = false