开发者

rspec testing ajax response (should render a partial)

开发者 https://www.devze.com 2023-02-24 23:03 出处:网络
I want to test that my controller action is rendering a partial. I\'ve poked around and I can\'t seem to find anything that works.

I want to test that my controller action is rendering a partial.

I've poked around and I can't seem to find anything that works.

create action:

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

spec:

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


If you're looking for a REAL answer... (i.e. entirely in RSpec and not using Capybara), the RSpec documentation says that render_template is a wrapper on assert_template. assert_template (according to the docs) also indicates that you can check that a partial was rendered by including the :partial key.

Give this a go...

it { should render_template(:partial => '_partialname') }


Update see bluefish's answer below, it seems to be the correct answer

Would you consider using Capybara for your integration testing? I found ajax difficult to test with rspec alone. In your case I'm not even sure you are getting a response back yet. In capybara it waits for the ajax call to finish and you can call the page.has_xxxx to see if it was 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


another great way to test your ajax controller method is to check the assignments which are later used to render the result. Here is a little 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号