Как вы можете выполнять функциональные тесты в ответах JavaScript? - PullRequest
0 голосов
/ 01 февраля 2011

Я заметил, что в Rails довольно распространено рендерить текст для js-запросов с текстом, встроенным в вызов метода jquery, чтобы вставить его в DOM.

// javascript code
$.getScript("/some_url");

// rails partial code, to make things more clear I have added some simple html
$("#some_id").text(unescape_javascript('<div id="foo">bar</div>'))

Мой вопрос: как вы выполняете assert_select или его эквивалент в функциональном тесте для текста ответа, подобного этому?

// 
class FooBarControllerTest < ...
  test "javascript response" do
     xhr :get, :new
     // how could I test the div here
     assert_select "#foo", "bar"  // this doesn't work
  end
end

** Обновлен код, чтобы сделать это более понятным

Ответы [ 3 ]

2 голосов
/ 05 февраля 2011

После некоторого возни с этим у меня работает. Самая сложная часть - очистка всех символов с разделителями, таких как \ t, \ n и \, перед созданием объекта HTML :: Document.

# wrapper method around the native assert_select method that extracts out the html
# from raw html text that is embedded within javascript code.
# ex.
#   $('body').append("<div id=\"edit_post_form_container\" class=\"active modal_form_container\">
#     <a href=\"#\" class=\"close\">
#       <img alt=\"Close\" height=\"16\" src=\"/images/close.png?1293730609\" width=\"16\" />
#     <\/a>
#     <form accept-charset=\"UTF-8\" action=\"/posts/1023110335\" .../>")
#
# assert_js_select "input[type=?][name=?]", "text", "foo[bar]", :count => 1
# assert_js_select "textarea", "Some long text"
# assert_js_select "textarea[name=?]", "post_text", "Some long text"
# assert_js_select "textarea[name=?][class=?]", ["post_text", "css_class", "Some long text"
def assert_js_select(*args, &block)
  extracted_text = @response.body.match(/(\<.*\>)/)[0].
    gsub("\\n", "").gsub("\\t", "").gsub(/\\"/, '"').gsub("\\", '')
  if extracted_text.present?
    doc = HTML::Document.new(CGI::unescapeHTML(extracted_text)).root
    args.insert(0, doc)
    assert_select(*args, &block)
  else
    assert false, "Unable to extract any html from the js code."
  end
end
0 голосов
/ 25 апреля 2017

В Rails 4.x это работает для меня (хитрость в том, чтобы переопределить метод document_root_element во время спецификации / теста):

context "with assert_select" do
  def document_root_element
    Nokogiri::HTML::Document.parse(@html).root
  end

  it "works" do
    xhr :get, :new
    @html = response.body # or wherever the response HTML comes from
    assert_select "#foo", "bar" # should work now
  end
end
0 голосов
/ 01 февраля 2011

Я не знаю, как бы вы запросили его у rails, но с ajax и jquery все будет выглядеть так:

$.ajax({
        type: 'POST',
        url: 'getstring.php',
        data: '',
        success: function(server_response){
            if(server_response){
                eval(server_response);
            }
            else{

            }
        }
    });

вам нужно будет eval , поэтому просто поместите свою строку так, чтобыдолжен быть запущен как javascript внутри eval ();

...