1

私は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
4

2 に答える 2

2

私は次のコードをテストしていないので、猫を殺すことができませんでしたが、投票のユーザーが投稿のユーザーと同じである場合は、エラーを追加してカスタム検証を試してください。

明らかな理由でユーザーまたは投稿がnilの場合に戻ることに注意してください。

# 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

ルビーはわかりませんが、サインインしたユーザーが投稿したユーザーと一致するかどうかを確認する必要があります。もしそうなら、投票の要求を拒否します。

これが役に立たない場合は申し訳ありません:)

于 2012-07-16T19:10:31.597 に答える