代码之家  ›  专栏  ›  技术社区  ›  user9601213

Rails模型测试错误/失败

  •  1
  • user9601213  · 技术社区  · 7 年前

    首先,我要说的是,我对Rails的测试相当陌生。我在考试中遇到了一些错误,我不知道为什么。

    rails test:models
    Run options: --seed 21021
    
    # Running:
    
    F
    
    Failure:
    UserTest#test_user_should_be_valid [/home/ubuntu/workspace/test/models/user_test.rb:9]:
    Expected false to be truthy.
    
    
    bin/rails test test/models/user_test.rb:8
    
    E
    
    Error:
    PostTest#test_post_should_be_valid:
    ArgumentError: When assigning attributes, you must pass a hash as an argument.
        test/models/post_test.rb:5:in `setup'
    
    
    bin/rails test test/models/post_test.rb:8
    
    
    
    Finished in 0.237740s, 8.4126 runs/s, 4.2063 assertions/s.
    2 runs, 1 assertions, 1 failures, 1 errors, 0 skips
    

    这是密码

    user\u测试

    require 'test_helper'
    
    class UserTest < ActiveSupport::TestCase
      def setup
        @user=User.new(email:"fo0@hotmail.com")
      end
    
      test "user should be valid" do
        assert @user.valid?
      end
    end
    

    post\U测试

    require 'test_helper'
    
    class PostTest < ActiveSupport::TestCase
      def setup
        @post=Post.new(:ruby_meetup)
      end
    
      test "post should be valid" do
        assert @post.valid?
      end
    
    end
    

    使用者rb型

    class User < ApplicationRecord
      # Include default devise modules. Others available are:
      # :confirmable, :lockable, :timeoutable and :omniauthable
      devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :trackable, :validatable
             has_many :posts
    
              has_many :rsvps
              has_many :posts, through: :rsvps
    
              validates :email, presence: true
    
    end
    

    邮递rb型

    class Post < ApplicationRecord
    belongs_to :user
     geocoded_by :address
    after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
    reverse_geocoded_by :latitude, :longitude
    after_validation :reverse_geocode
    
    
      has_many :rsvps
      has_many :users, through: :rsvps
    
      validates :name, presence: true
    
    end
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   jvillian    7 年前

    因为你没有展示你的 User 模型,不可能知道它为什么无效。但是,在测试中,您可以执行以下操作:

    puts @user.errors.full_messages
    

    看看有什么问题。

    在第二个错误上,错误消息会准确地告诉您出了什么问题。你没有通过 hash new ,您正在传递一个符号:

    def setup
      @post=Post.new(:ruby_meetup)
    end
    

    :ruby_meetup 应该是这样的:

    ruby_meetup: 'some_value'
    
        2
  •  0
  •   user9601213 user9601213    7 年前

    错误已解决。我将此代码放在我的user\u测试中。rb型

    assert @user.valid?, @user.errors.full_messages
    

    并修复了密码为空的错误。

    谢谢大家的帮助,我真的很感激。