【问题标题】:rails post test model errorrails post test 模型错误
【发布时间】:2018-05-14 20:19:04
【问题描述】:

这就是我遇到的错误

.F

失败: PostTest#test_post_should_be_valid [/home/ubuntu/workspace/test/models/post_test.rb:9]: ["用户必须存在"]

我不确定“用户必须存在”是什么意思,因为我很确定具有 user_id 的用户确实存在。 这是我的代码

post_test.rb

require 'test_helper'

class PostTest < ActiveSupport::TestCase
  def setup
    @post=Post.new(user_id: "1",name:"ruby meetup")
  end

  test "post should be valid" do
    assert @post.valid?, @post.errors.full_messages
  end

end

post.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

我不确定这是否会有所帮助,但我还将包括我的用户测试和用户模型。

user_test.rb

require 'test_helper'

class UserTest < ActiveSupport::TestCase
  def setup
    @user=User.new(email:"fo30@hotmail.com", password: "h3h3123")
  end


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

user.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

任何帮助都将不胜感激,因为我最近才开始在 Rails 中进行测试。

【问题讨论】:

    标签: ruby-on-rails ruby unit-testing


    【解决方案1】:

    User.new 在内存中创建一个新用户,但不在数据库中。它没有有效的id 来填充user_id

    试试User.create!

    接下来,数据库记录不会在测试运行之间共享。 Rails 通过在每个测试用例之后整理记录来尝试“测试隔离”。因此,您的 PostTest 需要自己的 User.create! 副本。

    完成这项工作后,查找“rails 测试装置”的一般主题...

    【讨论】:

    • 好吧,我已经按照你说的做了,但我仍然遇到同样的错误
    • 您是否修复了PostTest#index,因此它还创建了一个用户,并将该用户的id 分配给user_id
    • 好的,我只需将 user_id 复制到我的用户 yml 文件中,现在一切正常,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    相关资源
    最近更新 更多