Rspec testing ajax response (should do partial)

I want to check that my controller action is partial.

I poked, and I can not find anything that works.

create action:

def create @project = Project.new... respond_to do |format| if @project.save format.js { render :partial => "projects/form" } end end end 

Specification:

 it "should save and render partial" do .... #I expected/hoped this would work response.should render_partial("projects/form") #or even hopefully response.should render_template("projects/form") #no dice end 
+8
ruby ruby-on-rails rspec
source share
3 answers

Update, see below the answer to the blue question, this is the correct answer

Could you use Capybara to test integration? I found that ajax is hard to test with rspec only. In your case, I'm not even sure that you still got the answer. In capybara, it waits for the ajax call to complete, and you can call page.has_xxxx to see if it is updated. Here is an example:

 it "should flash a successful message" do visit edit_gallery_path(@gallery) fill_in "gallery_name", :with => "testvalue" click_button("Update") page.has_selector?("div#flash", :text => "Gallery updated.") page.has_content?("Gallery updated") click_link "Sign out" end 
+2
source share

If you are looking for a REAL answer ... (i.e. completely in RSpec and not using Capybara), the RSpec documentation says render_template is a wrapper on assert_template. assert_template ( according to the docs ) also indicates that you can verify that the partial part was displayed, including the partial key.

Give it back ...

 it { should render_template(:partial => '_partialname') } 
+48
source share

Another great way to test your ajax controller method is to check assignments, which are later used to render the result. Here is a small example:

controller

 def do_something @awesome_result = Awesomeness.generete(params) end 

Jbuilder

 json.(@awesome_result, :foo, :bar) 

Rspec controller test

 describe :do_something do before do @valid_params{"foo" => "bar"} end it "should assign awesome result" do xhr :post, :do_something, @valid_params assigns['awesome_result'].should_not be_nil end end 
+1
source share

All Articles