私はプロジェクト、タスク、およびサブタスクを設定しました。これらはすべてコメント可能です。コメント モデルを作成してモデルを接続しましたが、ユーザー ID を適切に検証する方法と、Rpsec と Factory Girl を使用してモデル コードをテストする方法がわかりません。私もDeviseを使っています。
コメントの移行
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> に対して未定義のメソッド `user' を示すエラー メッセージで失敗しています。しかし、このようにユーザーIDを渡すと...
FactoryGirl.build(:comment, :user => confirmed_user).should be_valid
ユーザーIDを一括割り当て可能な属性として設定する必要がありますが、それは望ましくありません(一部のユーザーがその属性をいじって変更する可能性があると考えてください)。これを適切にテストして検証する方法は? また、ポリモーフィックを行うのはこれが初めてなので、ばかげたことを見つけたら教えてください。
編集。1つの答えが示唆したように、私は今これを行いました。残念ながら、同じエラーが返されます。
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