1

我有三个模型UserPostVote

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

2 回答 2

2

我没有测试以下代码,因此它无法工作甚至杀死你的猫,但如果投票的用户与帖子的用户相同,请尝试使用自定义验证添加错误。

请注意,如果用户或帖子出于明显的原因为零,我会返回。

# In your vote model
validate :users_cant_vote_their_posts

def users_cant_vote_their_posts
  return if user.nil? or post.nil?
  if user_id == post.user_id
    errors[:base] = "A user can't vote their posts"
  end
end

编辑:这是一个可能的测试,这里我使用 FactoryGirl 来生成选票。再次,此代码未经测试(对不起双关语)

describe Vote do
  subject { vote }

  let!(:vote) { FactoryGirl.build(:vote) }

  it 'from factory should be valid' do
    should be_valid
  end

  context 'when user try to double vote' do
    before do
      # Create another vote from user to post
      FactoryGirl.create(:vote, :user => vote.user, :post => vote.post)
    end

    it { should_not be_valid }
  end

  context 'when user try to vote his posts' do
    before do
      # Set the user whom voted to the post's owner
      vote.user = vote.post.user
    end

    it { should_not be_valid }
  end

end
于 2012-07-16T19:14:56.787 回答
0

我不知道 ruby​​,但您应该检查登录的用户是否与发帖的用户匹配。如果确实如此,请拒绝投票请求。

对不起,如果这没有帮助:)

于 2012-07-16T19:10:31.597 回答