我有三个模型User,Post,Vote
我需要不允许用户为自己的帖子投票。我如何在我的模型中制作它并在 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