我有一个名为voteable的投票模型的多态关联。这是它的控制器:
class VotesController < ApplicationController
def create
begin
@voteable = get_voteable
@rating = Rating.find(params[:rating_id])
@user = current_user
@vote = Vote.new()
@vote.voteable = @voteable
@vote.rating = @rating
@vote.user = @user
rescue ActiveRecord::RecordNotFound
redirect_to stories_path, flash:{error: t('controllers.votes.create.flash.error')}
return
end
respond_to do |format|
if @vote.save
format.html { redirect_to story_path(@voteable), notice: t('controllers.votes.create.flash.success') }
end
end
end
private
def get_voteable
@voteable = params[:voteable].classify.constantize.find(voteable_id)
end
def voteable_id
params[(params[:voteable].singularize + "_id").to_sym]
end
end
路由是这样的:
resources :stories do
resources :votes, :defaults => { :voteable => 'stories' }
end
这是控制器的测试:
before do
@story = FactoryGirl.create(:story)
@rating = FactoryGirl.create(:rating)
end
it 'creates vote' do
post :create, story_id: @story.id, rating_id: @rating
flash[:notice].should eq(I18n.t('controllers.votes.create.flash.success'))
end
测试失败:
Failure/Error: post :create, story_id: @story.id, rating_id: @rating
ActionController::RoutingError:
No route matches {:story_id=>"1", :rating_id=>"1", :controller=
>"votes", :action=>"create"}
任何人都可以解释我如何在测试中使用post
?
我必须提到一切都在生产上正常工作。
答案 0 :(得分:0)
刚刚写了这样的测试并且它通过了:
it 'lets all users to create vote', focus: true do
post :create, story_id: @story, rating_id: @rating, voteable: "stories"
flash[:notice].should eq(I18n.t('controllers.votes.create.flash.success'))
end