# Rspec to xhr

**URL:** <https://www.ruby-forum.com/t/rspec-to-xhr/168838>\
**Category:** Rails\
**Created:** [May 26, 2009, 3:55pm UTC](https://www.ruby-forum.com/t/rspec-to-xhr/168838 "2009-05-26T15:55:05Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![huang\_zhimin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/54ee81/32.png) [@huang\_zhimin](https://www.ruby-forum.com/u/huang_zhimin)\
**Post date:** [May 26, 2009, 3:55pm UTC](https://www.ruby-forum.com/t/rspec-to-xhr/168838/1 "2009-05-26T15:55:05Z")

</div>

when i want to test an ajax action, it always can’t passed. The action  
code  
is:

# POST /posts/:id/comments

def create  
@comment = @post.comments.build(params[:comment])

```
if @comment.save
  flash[:notice] = 'Comment was successfully created.'
  render :update do |page|
    page.insert_html :bottom, 'comments', :partial => 

```

‘posts/comment’,  
:object =\> @comment  
page.replace\_html ‘comment’, :partial =\> ‘comment’, :object =\>  
Comment.new  
end  
else  
render :update do |page|  
page.replace\_html ‘comment’, :partial =\> ‘comment’, :object =\>  
@comment  
end  
end  
end

and the test code is:

describe “handling POST /posts/:id/comments” do

```
before(:each) do
  @post = Post.new
  @comment = Comment.new
  Post.stubs(:find).returns(@post)
  @post.comments.stubs(:build).returns(@comment)
end

it "with successful save" do
  @comment.expects(:save).returns(true)
  xhr :post, :create, :post_id => @post.id, :comment => {}
  response.should have_rjs(:insert_html, :bottom, 'comments')
  response.should have_rjs(:replace_html, 'comment')
end

it "with failed save" do
  @comment.expects(:save).returns(false)
  xhr :post, :create, :post_id => @post.id, :comment => {}
  response.should have_rjs(:replace_html, 'comment')
end

```

end

The result is:  
1)  
‘CommentsController handling DELETE /comments/:id with successful  
destroy’  
FAILED  
No RJS statement that removes ‘comment\_’ was rendered.  
./spec/controllers/comments\_controller\_spec.rb:38:

1. 

‘CommentsController handling POST /posts/:id/comments with successful  
save’  
FAILED  
bottom.  
./spec/controllers/comments\_controller\_spec.rb:16:

But I can do it successfully by browser. So I think there’s something  
wrong  
with my rspec codes. Can anyone help me? Thanks in advanced.

Best Regard,  
Richard

–  
My home: [http://www.huangzhimin.com](http://www.huangzhimin.com)
