我已经设置了项目、任务和子任务,所有这些都是可评论的。我创建了评论模型并连接了模型,但不知道如何正确验证用户 ID 以及如何使用 Rpsec 和 Factory Girl 测试模型代码。我也在使用设计。
评论迁移
1 class CreateComments < ActiveRecord::Migration
2 def change
3 create_table :comments do |t|
4 t.references :user, :null => false
5 t.text :comment, :null => false,
6 :limit => 500
7 t.references :commentable, :polymorphic => true
8 # upper line is a shortcut for this
9 # t.integer :commentable_id
10 # t.string :commentable_type
11 t.timestamps
12 end
13 add_index :comments, :user_id
14 add_index :comments, :commentable_id
15 end
16 end
评论模型
1 class Comment < ActiveRecord::Base
2
3 # RELATIONSHIPS
4 belongs_to :commentable, :polymorphic => true
5 belongs_to :user
6 # VALIDATIONS
7 validates :user, :presence => true
validates :commentable, :presence => true
8 validates :comment, :presence => true,
9 :length => { :maximum => 500 }
10
11 # ATTRIBUTE ASSIGNMENT
12 attr_accessible :comment
13
14 end
用户模型
1 class User < ActiveRecord::Base
2
3 # RELATIONSHIPS
4 has_many :synapses, :dependent => :destroy
5 has_many :projects, :through => :synapses
6
7 has_many :vesicles, :dependent => :destroy
8 has_many :tasks, :through => :vesicles
9
10 has_many :subvesicles, :dependent => :destroy
11 has_many :subtasks, :through => :subvesicles, :dependent => :nullify
12
13 has_many :comments, :dependent => :destroy
14
15 # VALIDATIONS
16 validates :name, :presence => true,
17 :uniqueness => true
18
19 # ATTRIBUTE ASSIGNMENT
20 attr_accessible :name, :email, :password, :password_confirmation, :remember_me
21
22 # DEVISE MODULES
23 # Include default devise modules. Others available are:
24 # :token_authenticatable, :encryptable, :lockable, :timeoutable and :omniauthable
25 devise :database_authenticatable, :registerable,
26 :recoverable, :rememberable, :trackable, :validatable,
27 :confirmable
28
29 end
评论工厂
105 factory :comment do
106 comment "This is some generic comment with some generic content"
107 end
评论型号规格
1 require 'spec_helper'
2
3 describe Comment do
4
5 it 'Should create new comment' do
6 FactoryGirl.build(:comment).should be_valid
7 end
8
9 it 'Should respond to method provided by polymorphism to find its parent' do
10 FactoryGirl.build(:comment).should respond_to(:commentable)
11 end
12
13 end
此第一个测试当前失败,错误消息为 #Comment:0xa88c354> 的未定义方法“用户”。但是如果我像这样传递用户ID......
FactoryGirl.build(:comment, :user => confirmed_user).should be_valid
比我应该将用户 ID 设置为可批量分配的属性,而我不希望这样(认为某些用户可能会弄乱该属性并更改它)。如何正确测试和验证这一点?另外,这是我第一次做多态,所以如果你看到任何愚蠢的事情,请告诉我。
编辑。我现在已经按照建议的一个答案这样做了。不幸的是,它返回相同的错误。
5 it 'Should create new comment' do
6 confirmed_user = FactoryGirl.build(:confirmed_user)
7 FactoryGirl.build(:comment, :commentable => confirmed_user).should be_valid
8 end