目前通过奥丁项目课程学习ROR。作为“PROJECT:积极记录建设”的一部分,我设置了三个基本模型:用户,帖子,评论。
在帖子和评论中,我的基本“帖子/评论是有效的”测试失败(错误预期真实性),但所有特定测试都通过,例如PostTest的代码:
require 'test_helper'
class PostTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
def setup
@post = Post.new(title: "Hello World", body: "Hello world, it's nice to
meet you", user_id: 1)
end
test "Post is valid" do
assert @post.valid?
end
test "Post title is not blank" do
@post.title = ""
assert_not @post.valid?
end
test "Post title is less than 40 char" do
@post.title = "a"*51
assert_not @post.valid?
end
test "Post body is not blank" do
@post.body = ""
assert_not @post.valid?
end
test "Post has user_id" do
@post.user_id = ""
assert_not @post.valid?
end
end
我感到困惑的原因是,如果我使用rails console手动创建与上面#setup
相同的帖子,那么valid?
方法会正确返回true
。此外,用户模型设置与#setup
和user is valid
测试的形式完全相同。我看到的唯一区别是用户has_many :posts
作为帖子belong_to :user
对于参考,Post模型是:
class Post < ApplicationRecord
validates :title, presence: true, length: {maximum: 40}
validates :body, presence: true
validates :user_id, presence: true
belongs_to :user
has_many :comments
end
答案 0 :(得分:0)
您是否正在为您的用户使用灯具,或者您如何知道ID为1的用户记录?
如果您使用灯具,则应在设置中创建用户:
<div id="delete_department" class="modal custom-modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content modal-md">
<div class="modal-header">
<h4 class="modal-title">Delete Department</h4>
</div>
<div class="modal-body card-box">
<p>Are you sure want to delete this?</p>
<div class="m-t-20 text-left">
<a href="#" class="btn btn-default" data-dismiss="modal">Close</a>
<button type="submit" class="btn btn-danger" >Delete</button>
</div>
</div>
</div>
</div>
</div>
<div id="edit_department" class="modal custom-modal fade" role="dialog">
<div class="modal-dialog">
<button type="button" class="close" data-dismiss="modal" (click)="edit(list)">×</button>
<div class="modal-content modal-md">
<div class="modal-header">
<h4 class="modal-title">Edit Department</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label>Department Name <span class="text-danger">*</span></label>
<input class="form-control" value="IT Management" type="text">
</div>
<div class="m-t-20 text-center">
<button class="btn btn-primary btn-lg" (click)="edit(list)">Save Changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
详情了解灯具:http://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures