【发布时间】:2016-01-20 19:09:29
【问题描述】:
我在测试我的 CommentsController 时遇到了这个问题:
失败/错误:redirect_to user_path(@comment.user),注意:'你的 评论已成功添加! ActionController::UrlGenerationError: 没有路线匹配 {:action=>"show", :controller=>"users", :id=>nil} 缺少必需的键:[:id]
这是我在控制器中的方法:
def create
if params[:parent_id].to_i > 0
parent = Comment.find_by_id(params[:comment].delete(:parent_id))
@comment = parent.children.build(comment_params)
else
@comment = Comment.new(comment_params)
end
@comment.author_id = current_user.id
if @comment.save
redirect_to user_path(@comment.user), notice: 'Your comment was successfully added!'
else
redirect_to user_path(@comment.user), notice: @comment.errors.full_messages.join
end
end
这是我的 RSpec:
context "User logged in" do
before :each do
@user = create(:user)
sign_in @user
end
let(:comment) { create(:comment, user: @user, author_id: @user.id) }
let(:comment_child) { create(:comment_child, user: @user, author_id: @user.id, parent_id: comment.id) }
describe "POST #create" do
context "with valid attributes" do
it "saves the new comment object" do
expect{ post :create, comment: attributes_for(:comment), id: @user.id}.to change(Comment, :count).by(1)
end
it "redirect to :show view " do
post :create, comment: attributes_for(:comment), user: @user
expect(response).to redirect_to user_path(comment.user)
end
end
...
end
end
我的评论型号:
class Comment < ActiveRecord::Base
belongs_to :user
acts_as_tree order: 'created_at DESC'
VALID_REGEX = /\A^[\w \.\-@:),.!?"']*$\Z/
validates :body, presence: true, length: { in: 2..240}, format: { with: VALID_REGEX }
end
如何将user_id 添加到该请求中?当我将控制器 redirect_to user_path(@comment.user) 中的代码更改为 redirect_to user_path(current_user) 时 - 测试通过。我可以 redirect_to cmets 控制器中的用户吗?有没有做对的可能性?谢谢你的时间。
【问题讨论】:
标签: ruby-on-rails ruby rspec