Reputation:
So this is the error I'm getting
.F
Failure: PostTest#test_post_should_be_valid [/home/ubuntu/workspace/test/models/post_test.rb:9]: ["User must exist"]
I'm not sure what it means by "user must exist" since I'm pretty sure a user with an user_id one does exist. heres my code
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
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
I'm not sure if this will be helpful but I'm also going to include my user test and user model.
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user=User.new(email:"[email protected]", password: "h3h3123")
end
test "user should be valid" do
assert @user.valid?, @user.errors.full_messages
end
end
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
Any help will greatly be appreciated as I just recently started testing in rails.
Upvotes: 0
Views: 70
Reputation: 5343
User.new
creates a new user in memory, but not in the database. It won't have a valid id
to populate user_id
.
Try User.create!
.
Next, database records are not shared between test runs. Rails attempts "test isolation" by zilching records after each test case. So your PostTest needs its own copy of User.create!
.
After you get this working, look up the general topic of "rails test fixtures"...
Upvotes: 1