How to test Ajax functionality

Hi,

I have ‘Ajaxified’ some functionality that hides a resource in my Rails app (https://github.com/acandael/posplus-rails)

the ‘Hide’ controller action just toggles the visible property of a Researcher object.

In the view, when an administrator clicks the show link of a Researcher object, the visible property of the Researcher object will be set to ‘true’ and the link label text will change to ‘Hide’. When and administrator clicks the ‘Hide’ link, the visible property of the Researcher will be set to ‘false’ and the link label text will change to false.

My controller ‘Hide’ action looks like this:

app/controllers/admin/researchers_controller.rb
...
def hide
  @researcher = Researcher.find(params[:id])
  @researcher.toggle_visibility!
  render "hide.js.erb"
end

the toggle_visibility helper method looks like this:

app/models/concerns/hideable.rb
...
def toggle_visibility!
  if visible?
    update_attribute(:visible, false)
  else
    update_attribute(:visible, true)
  end
end

In my View, I implement the Hide link like this:

app/views/admin/researchers/index.html.erb
...
<%= link_to toggle_visibility(researcher), hide_admin_researcher_path(researcher), method: :patch, remote: true, id: dom_id(researcher) %>

The Javasscript Template looks like this:

app/views/admin/researchers/hide.js.erb
$("#researcher_<%= @researcher.id %>").text("<%= toggle_visibility(@researcher) %>");

This all works fine, but I also would like to write a test for this, for instance to test that when an administrator clicks the Hide link, the link label text effectively changed to ‘Show’ and vice verse.

I’m not proficient in testing Javascript though, so I could use some guidance in setting up this test in Rspec.

Thanks for your help,

Anthony

Seem that my test are just running fine:

  scenario 'Admin hides researcher' do
    click_link "Hide"
    expect(page).to have_css 'p', text: "The researcher #{ @researcher.name } is now hidden"
    @researcher.reload
    expect(@researcher.visible).to be_false
  end

The only thing I needed to change was the way that my Flash message is set, as a controller can’t send a Flash notice, as no redirect is happening.

So I set the Flash message in my Javascript template:

app/views/admin/researchers/hide.js.erb
$("#researcher_<%= @researcher.id %>").text("<%= toggle_visibility(@researcher) %>");
if (<%= @researcher.visible %>) {
  $(".messages").empty().append("<p class='notice'>The researcher <%= @researcher.name %> is now      visible</p>");
}
else {
  $(".messages").empty().append("<p class='notice'>The researcher <%= @researcher.name %> is now   hidden</p>");
}

my tests are working fine now