rails, getJSON, and jasmine

Task:
When user selects a country from the country dropdown,
get the new terms and conditions links according to the selected country,
and update the current terms and conditions links with the new ones.

controller

def update_policy_links
    respond_to do |format|
      format.js {
        render :json => {:updated_terms_link => 
                          return_policy_link("terms", country_preference),
                         :updated_privacy_link => 
                          return_policy_link("privacy", country_preference),
                         :updated_electronic_link => 
                          return_policy_link("electronic", country_preference)}
      }
    end
end

country_preference: a cookie that stores the latest country user selected
return_policy_link: check out the previous post on default value & nil guard

routes

get '/update_policy_links/:country' => "enrollment/user#update_policy_links", :constraints => {:country => /[a-zA-Z]{2}/}

note: we’re passing in country as a param for other usage which I won’t go over here…

javascript

$("#new_vuser").on('blur', '#user_countryCode', function(){
    country_selected = $(this).val();

    $.getJSON("/update_policy_links/" + country_selected + "?locale=" + I18n.locale, function(data){
          $(".terms_link, #terms_link").attr('href', data.updated_terms_link);
          $(".privacy_link, #privacy_link").attr('href', data.updated_privacy_link);
          $(".electronic_link").attr('href', data.updated_electronic_link);
    });
});

jasmine

describe("on_select_change", function(){
    it("should update the terms and condition links", function(){

        var links ={
            updated_terms_link : "/pages/terms",
            updated_privacy_link : "/pages/privacy",
            updated_electronic_link : "/pages/electronic"
        };

        spyOn($, 'getJSON').andCallFake(function(url,data){ data(links); });
        $('#user_countryCode').blur();

        expect($.getJSON).wasCalled();
        expect($('.terms_link, #terms_link')).toHaveAttr('href',"/pages/terms");
        expect($('.privacy_link, #privacy_link')).toHaveAttr('href',"/pages/privacy");
        expect($('.electronic_link')).toHaveAttr('href',"/pages/electronic");
    });
})

would you like to leave a comment?