这是我指定的代码:
def vote_up
get_vote
@vote.value += 1 unless @vote.value == 1
@vote.save
respond_to do |format|
format.js { render :action => "vote", :layout => false }
end
end
看起来很简单。这就是我要指定的内容:
it "should vote up" do
@mock_cat = Factory.create(:category)
Category.stub(:mock_cat)
@mock_post = Factory.create(:post)
Post.stub(:current_post).and_return(@mock_post)
@vote = Factory(:vote)
get :vote_up, :id => @vote
@vote.reload.value.should == 1
end
它返回这个:
undefined method `to_i' for #<Vote:0x1052a4af8>
我真的不知道为什么。如果我将 mock_vote 存根为 (:vote),它不会通过控制器方法运行并获得 +1 归因于它吗?
更新
这是我的 posts_controller.rb 中的私有方法
private
def get_vote
current_post = Post.all.detect{|r| r.id == params[:id].to_i}
@post = current_post
@vote = current_post.votes.find_by_user_id(current_user.id)
unless @vote
@vote = Vote.create(:user_id => current_user.id, :value => 0)
current_post.votes << @vote
end
end
回答:
it "should vote up" do
@mock_cat = Factory.create(:category)
Category.stub(:mock_cat)
@post = Factory(:post)
get :vote_up, :id => @post.id
@post.reload.vote_score.should == 1
end