私は3つのモデルを持っていますユーザー、投稿、投票
ユーザーが自分の投稿に投票することを許可しないようにする必要があります。モデルでこれを作成し、Rspecでテストするにはどうすればよいですか?
ポストモデル:
class Post < ActiveRecord::Base
attr_accessible :title, :main_text, :video, :photo, :tag
validates :title, presence: true, length: {minimum: 1, maximum: 200}
validates :main_text, presence: true, length: {minimum: 1}
belongs_to :user
has_many :votes
end
ユーザーモデル:
class User < ActiveRecord::Base
attr_accessible :name, :email, :bio
has_many :posts
has_many :votes
validates :name, presence: true, length: {minimum: 1, maximum: 120}
validates :email, presence: true, length: {minimum: 5, maximum: 250}, uniqueness: true,
format: {:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i}
end
投票モデル:
class Vote < ActiveRecord::Base
attr_accessible :user_id, :post_id, :units
belongs_to :user
belongs_to :post
validates :post_id, uniqueness: {scope: :user_id} #does not allow user to vote for the same post twice
end
投票のための私のスペックテスト:
require 'spec_helper'
describe Vote do
it "does not allow user to vote for the same post twice" do
user = User.create(name: "Nik", email: "nik@google.com" )
post = Post.create(title: "New Post", main_text: "Many, many, many...")
vote1 = Vote.create(user_id: user.id, post_id: post.id)
vote1.errors.should be_empty
vote2 = Vote.create(user_id: user.id, post_id: post.id)
vote2.errors.should_not be_empty
end
it "does not allow user to vote for his own post" do
user = User.create(name:"Nik", email:"a@a.ru")
post = Post.create(user_id: user.id, title: "New Post", main_text: "Many, many, many...")
vote1 = Vote.create(user_id: user.id, post_id: post.id)
vote1.errors.should_not be_empty
end
end