Alexandre
Alexandre

Reputation: 13328

How do I test this code in RSpec?

Here is the method that called only via ajax in Ruby on Rails 3.2.2

def some_ajax_action
    @user = User.find_by_id(params[:id])
    @user_list = User.find_all_by_parent_id(params[:id])
    respond_to do |format|
      format.js
    end
  end

I wonder is it neccessary (or possible) to test it with RSpec? Any thoughts?

Upvotes: 1

Views: 85

Answers (1)

Chris Salzberg
Chris Salzberg

Reputation: 27374

How about:

before do
  User.stub(:find_by_id)
  User.stub(:find_all_by_parent)
end

it "finds the user" do
  User.should_receive(:find_by_id).with("37")
  xhr <HTTP VERB>, :some_ajax_action, :id => "37"
end

it "finds the user list" do
  User.should_receive(:find_all_by_parent).with("37")
  xhr <HTTP VERB>, :some_ajax_action, :id => "37"
end

Replace <HTTP VERB> by whatever is in your routes.rb for these ajax calls, e.g. if you have

get 'some_ajax_action'

then the first one would be xhr :get, :some_ajax_action, :id => "37".

Upvotes: 2

Related Questions