2014-11-16 2 views
0

При запуске rake test, я получаю эту ошибку: ActionController::UrlGenerationErrorКомментарии conrtoller тест ActionController :: UrlGenerationError

мой routes.rb

resources :posts do 
    resources :comments, only: [ :create,:destroy ] 
    end 

comments.yml

one: 
    body: "comment one" 
    user: users(:paul) 
    post: posts(:one) 

comments_controller_test.rb

def setup 
    @comment = comments(:one) 
    end 

    test "should redierct create when not signed in" do 
    assert_no_difference "Comment.count" do 
     post :create, comment: @comment.attributes 
    end 
    assert_redirected_to signin_url 
    end 

comments_controller.rb

def create 
    @comment = @post.comments.build(comment_params.merge(user: current_user)) 
    @comment.save 
    @comments = @post.comments.all 
    respond_to do |format| 
     format.html { redirect_to @post } 
     format.js 
    end 
    end 

Полное сообщение об ошибке

ERROR["test_should_redierct_create_when_not_signed_in", CommentsControllerTest, 0.444971] test_should_redierct_create_when_not_signed_in#CommentsControllerTest (0.44s) ActionController::UrlGenerationError:
ActionController::UrlGenerationError: No route matches {:action=>"create", :comment=>{"id"=>"980190962", "body"=>"comment one", "post_id"=>"849819558", "user_id"=>"293831562", "created_at"=>"2014-11-16 10:45:03 UTC", "updated_at"=>"2014-11-16 10:45:03 UTC"}, :controller=>"comments"}

Как мне изменить мой тестовый код?

+0

не уверен, но попробуйте заменить 'redirect_to @ Post' в comments_controller с 'redirect_to [@ post, @ comments]'! – Nimir

+0

Это не работает, я думаю 'post: create, comment: @ comment.attributes', возможно, является основной причиной ошибки. –

ответ

0

Я думаю, что вам нужно явно сказать о родительском Индентификационный (POST_ID), поэтому рельсы могут сформировать правильный почтовый путь, попробовать что-то вроде:

post :create, comment: @comment.attributes, post_id: @comment.post_id 
+0

Спасибо, он работает! Но у меня все еще есть сомнения, почему '@ comment.attributes' не содержат' post_id'? –

+0

он содержит его (как в сообщении с ошибкой сообщения об ошибке), но при запросе на создание почтового запроса Rails не может определить правильный путь >> post_comments_url, не передавая post_id в качестве параметра. Постарайтесь узнать больше о маршрутизации вложенных ресурсов .. надеюсь, что это поможет! – Nimir

+0

Понял, спасибо за ваше объяснение. –

Смежные вопросы