0

親モデルのメンバールートを介して POST するポリモーフィック投票モデルがあります。各親にはコントローラーに「投票」メソッドがあり、コントローラーテストでこのアクションをテストしようとしています。以下のコードを参照してください。簡単にするために、コントローラーのアクションとテストの 1 つを示します。

私の努力と、expect proc への試みに関係なく、このテストに合格することはできませんid: @answerid: @voteFactoryGirl.attributes_for(:vote, user_id: @user2)

factoryGirl.rb

FactoryGirl.define do
  factory :user do |u|
    u.sequence(:email) {|n| "test#{n}@hotmail.com"}
    u.sequence(:username) {|n| "tester#{n}" }
    u.password "password"
    u.password_confirmation "password" 
    u.remember_me true
    u.reputation 200
  end

factory :answer do
    user_id :user
    question_id :question
    body "you need to change your grip"
    votes_count 0
    correct true
  end

factory :vote do
    user_id :user
    votable_id :answer
    votable_type "Answer"
    value 1
  end

Answers_controller_spec.rb

describe "POST vote" do
    it "creates vote" do
      @user2 = FactoryGirl.create(:user)
      @answer = FactoryGirl.create(:answer)
      @vote = FactoryGirl.create(:vote)
      expect {
        post :vote, id: @vote 
      }.to change(Vote, :count).by(1)
      response.should be_success
    end
  end

テストの失敗

Failures:

  1) AnswersController POST vote creates vote
     Failure/Error: expect {
       count should have been changed by 1, but was changed by 0
     # ./spec/controllers/answers_controller_spec.rb:90:in `block (3 levels) in <top (required)>'

Finished in 2.01 seconds
9 examples, 1 failure

投票.rb

class Vote < ActiveRecord::Base

  attr_accessible :value, :votable_id, :votable_type
  belongs_to :votable, polymorphic: true
  belongs_to :user

  validates_inclusion_of :value, in: [1, -1]
  validates_presence_of :user_id, :value, :votable_id, :votable_type, :points
  validates_uniqueness_of :user_id, scope: :votable_id
  validates_uniqueness_of :value, scope: :votable_id

  before_save :create_points

  def create_points
    self.value == 1 ? self.points = 5 : self.points = -3
  end
end

ルート.rb

  resources :answers do 
    member { post :vote }
    member { put :correct }
    resources :comments, except: [:edit, :update]
  end

answer_controller.rb

 def vote 
  @vote = current_user.votes.build(value: params[:value], votable_id: params[:id], votable_type: "Answer")
    respond_to do |format|
    if @vote.save
      format.html { redirect_to :back, notice: "Vote submitted" }
      format.js
    else
      format.html { redirect_to :back, alert: "You can't vote on your own content" }
      format.js
    end
  end
end
4

1 に答える 1

1

idパラメータは回答の ID です。

post :vote, id: @answer.id

パラメータを渡す必要がある場合もありvalueます (「up」または「down」値でしょうか?)。

Voteモデルの検証など、テストが失敗する理由は他にもあるかもしれません。vote.savefalse を返す場合は、errorsコレクションを確認します。

以下のコメント:

valueをパラメータとしてpost仕様に渡す必要があります。また、投票が重複しているようです。おそらく@vote仕様で作成する必要はまったくありません。errorsコレクションは、によってvalid?呼び出されるメソッドによって設定されsaveます。

于 2013-06-19T10:14:51.293 に答える