2012-08-08 162 views
1

這裏是被稱爲只有通過AJAX在Ruby on Rails的3.2.2如何在RSpec中測試此代碼?

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 

使用RSpec來測試它的方法,我不知道是不是neccessary(或可能)?有什麼想法嗎?

回答

2

如何:

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 

通過無論是在你的routes.rb這些Ajax調用,例如更換<HTTP VERB>如果你有

get 'some_ajax_action' 

那麼第一個就是xhr :get, :some_ajax_action, :id => "37"