我有一个多态投票模型,它在其父模型上通过成员路由进行POST。每个父级在控制器中都有一个“投票”方法,我试图在我的控制器测试中测试这个动作。请查看下面的代码,为简单起见,显示一个控制器操作和测试。
无论我的努力如何,id: @answer
,id: @vote
,FactoryGirl.attributes_for(:vote, user_id: @user2)
进入expect proc,我都无法通过此测试。
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
vote.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
的routes.rb
resources :answers do
member { post :vote }
member { put :correct }
resources :comments, except: [:edit, :update]
end
answers_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
答案 0 :(得分:1)
id
参数是答案的ID:
post :vote, id: @answer.id
您可能还需要传递value
参数(可能是“向上”或“向下”值?)。
测试失败可能还有其他原因,例如: Vote
模型中的验证。如果vote.save
返回false,请检查errors
集合。
以下评论:
您需要将value
作为参数传递给规范中的post
。您似乎也有重复投票,您可能根本不需要在规范中创建@vote
。 errors
集合由valid?
方法填充,save
方法由{{1}}调用。