Reputation: 87220
Here's the thing, I have Article
and Category
models, where obviously article belongs to one category.
I want to have the option of creating a new category in the new Article's form, so I decided to use AJAX. The form looks very simple.
<%= form_for @category, :method => :post, :remote => true do |f| %>
<p>
<%= f.label :name %>
<%= f.text_field :name %>
</p>
<p class="button"><%= f.submit %></p>
<% end %>
same as the CategoriesController
class CategoriesController < ApplicationController
respond_to :js
def create
@category = Category.new(params[:category])
@saved = @category.save
end
end
and create.js.coffee
view template
if <%= @saved %>
$('#category_name').val ''
new_option = $("<option value='<%= @category.id %>'><%= @category.name %></option>").attr('selected', 'selected')
$('select#article_category_id').append(new_option).focus()
else
alert "Category already exists"
$('#category_name').val('').focus()
I've been using integration testing via request specs, as described in Ryan Bates' screencast, which seems to work just fine, e.g.
it "supports js", :js => true do
visit new_article_path
fill_in "category_name", :with => "foobar"
click_button "Add category"
page.should have_content("foobar")
end
The thing is, the controller is responding with a .js.coffe
template, so I can't really have view specs. Should I even bother with testing controllers when I have request specs in place?
And second part of the question. Is it a good practice to user .js.coffee
templates as a response from a controller? Shouldn't I just return a http status code or some JSON, and handle all of that on the client side, instead of generating JavaScript to execute on each response?
Upvotes: 0
Views: 217
Reputation: 115531
1) Request spec is here to test the result of your js. So you should test your controller to be sure it returns the proper values to your js.coffee
2) This is really a matter of taste. I really prefer using json + client side js: it's more scalable. But Rails templates could give the impression to have more organized code.
Upvotes: 1