rspec控制器规格测试后期行动
由于某种原因, post spec
工作正常,但post_comment_spec
测试失败。 post有很多post_comments,post_comment属于post。
错误:
1) Posts::PostCommentsController when user is logged in POST create with invalid attributes doesn't save the new product in the db Failure/Error: 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(""); $('.alert-danger').show(); $('ul.errors').show(); $("ul.errors").append($("").html("")); $('ul.errors').hide(); $('.alert-danger').hide(); $('.post-index').prepend(''); collectionPostEditDropdown(); $('.post-create-body').val(''); $('#img-prev').attr('src', "#"); $('#img-prev').addClass('hidden'); $('.btn-create-post').prop('disabled',true); $('.remove-post-preview').addClass('hidden');
post_comment的create.js.erb
$("#post-comment-text-area-").val(''); $(".post-comment-insert-").prepend(''); $(".best_in_place").best_in_place();
正如错误所述,对local_time_ago
的调用最终会尝试在nil上调用to_time
– 因此您的注释在updated_at
属性中没有任何内容。
在post_comments_controller.rb中 ,你为什么要注释掉#@post_comment.save!
?
什么是@post_comment.save
返回? 我怀疑保存由于某种原因失败了,但你仍然试图渲染create.js.erb
,它期待一个有效的@post_comment
对象。
编辑:当@post_comment.save
create.js.erb
失败时,你不应该渲染create.js.erb
,因为它期望一个有效的@post_comment
对象。 在这种情况下render json: nil, status: :ok
你可能想render json: nil, status: :ok
。