2016-04-28 3 views
0

По какой-то причине post spec работает нормально, но тест post_comment_spec не работает. Post имеет много post_comments, post_comment принадлежит сообщению.rspec Контроллер спецификации тестирование после действия

ошибка:

1) Posts::PostCommentsController when user is logged in POST create with invalid attributes doesn't save the new product in the db 
Failure/Error: <span class="post-comment-updated"><%= local_time_ago(post_comment.updated_at) %></span> 

ActionView::Template::Error: 
    undefined method `to_time' for nil:NilClass 

posts_controller

def create 
    @post = current_user.posts.new(post_params) 
    authorize @post 
    if @post.save 
    respond_to do |format| 
     format.js 
    end 
    else 
    respond_to do |format| 
     format.js 
    end 
    end 
end 

post_comments_controller

def create 
    @post = Post.find(params[:post_id]) 
    @post_comment = @post.post_comments.build(post_comment_params) 
    authorize @post_comment 
    @post_comment.user = current_user 
    #@post_comment.save! 
    if @post_comment.save 
    @post.send_post_comment_creation_notification(@post_comment) 
    @post_comment_reply = PostCommentReply.new 
    respond_to do |format| 
     format.js 
    end 
    else 
    respond_to do |format| 
     format.js 
    end 
    end 
end 

posts_controller_spec.rb

describe "POST create" do 
    let!(:profile) { create(:profile, user: @user) } 

    context "with invalid attributes" do 
    subject(:create_action) { xhr :post, :create, post: attributes_for(:post, user: @user, body: "") } 

    it "doesn't save the new product in the db" do 
     expect{ create_action }.to_not change{ Post.count } 
    end 
    end 
end 

post_comments_controller_spec.rb

describe "POST create" do 
    let!(:profile) { create(:profile, user: @user) } 
    let!(:post_instance) { create(:post, user: @user) } 

    context "with invalid attributes" do 
    subject(:create_action) { xhr :post, :create, post_id: post_instance.id, post_comment: attributes_for(:post_comment, post_id: post_instance.id, user: @user, body: "") } 

    it "doesn't save the new product in the db" do 
     expect{ create_action }.to_not change{ PostComment.count } 
    end 
    end 
end 

create.js.erb на пост

$("ul.errors").html(""); 
<% if @post.errors.any? %> 
    $('.alert-danger').show(); 
    $('ul.errors').show(); 
    <% @post.errors.full_messages.each do |message| %> 
    $("ul.errors").append($("<li />").html("<%= message.html_safe %>")); 
    <% end %> 
<% else %> 
    $('ul.errors').hide(); 
    $('.alert-danger').hide(); 
    $('.post-index').prepend('<%= j render @post %>'); 
    collectionPostEditDropdown(); 
    $('.post-create-body').val(''); 
    $('#img-prev').attr('src', "#"); 
    $('#img-prev').addClass('hidden'); 
    $('.btn-create-post').prop('disabled',true); 
    $('.remove-post-preview').addClass('hidden'); 
<% end %> 

create.js.erb для post_comment

<% unless @post_comment.errors.any? %> 
    $("#post-comment-text-area-<%= @post_comment.post_id%>").val(''); 
    $(".post-comment-insert-<%= @post_comment.post_id %>").prepend('<%= j render @post_comment %>'); 
    $(".best_in_place").best_in_place(); 
<% end %> 
+0

Neven, я действительно не задаю вопрос. –

+0

'post_comment' не сохраняется, поэтому' updated_at' is nil –

+0

Как я могу проверить его? Я имею в виду, что код в порядке, поскольку он будет отображаться только при правильном сохранении. –

ответ

1

Как говорится об ошибках, вызов local_time_ago концов попытаться позвонить to_time на nil - так что ваш комментарий не имеет ничего в своем атрибуте updated_at.

В post_comments_controller.rb, почему вы закомментировали #@post_comment.save!?

И что такое @post_comment.save возвращение? Я подозреваю, что сбой по какой-то причине сбой, но вы все еще пытаетесь сделать create.js.erb, который ожидает действительный объект @post_comment.

РЕДАКТИРОВАТЬ: create.js.erb: @post_comment.save не работает, так как он ожидает действительного объекта @post_comment. В этом случае вы, вероятно, захотите render json: nil, status: :ok.

+0

Брайан здесь оригинальная проблема: http://stackoverflow.com/questions/36924449/rspec-controller-spec-matchers/36925108?noredirect1_comment61412428_36925108 Я прокомментировал это, потому что, если я использую '@ post_comment.save!' Тоже , он отправляет ошибку проверки в тесте, которая является суперверткой. Кстати, я не понимаю, почему я положил его изначально, так как код работает правильно, как сейчас. Существует только проблема с тестом. –

+0

Ошибка проверки является проблемой здесь - поскольку сбой «save» вы пытаетесь отобразить 'create.js.erb' с неавторизованным объектом. Какова была ошибка проверки? – Brian

+0

Обновлен вопрос. «Тело не может быть пустым» было ошибкой, и это нормально, поскольку я пропускаю «body:» «в тесте. –

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