Testing fields added dynamically by cocoon using rspec and capybara

后端 未结 3 1309
春和景丽
春和景丽 2021-01-05 17:36

I was wondering whether anybody tests fields that were dynamically added by cocoon?

It\'s a great little time saver but all of the fields that are added dynamically

相关标签:
3条回答
  • 2021-01-05 17:54

    Afaik you could test for two things:

    • that the dynamic addition of the nested elements works
    • creating elements, filling it in and storing them in the database

    So assume the relevant part of your view looks like this (default example):

    #tasks
      = f.semantic_fields_for :tasks do |task|
        = render 'task_fields', :f => task
      .links
        = link_to_add_association 'add task', f, :tasks
    

    and your nested element looks like

    .nested-fields
      = f.input :description
      = f.input :done, :as => :boolean
      = link_to_remove_association "remove task", f 
    

    So normally you give it a class, i normally just test the count of elements on the page.

    So if one element is already there, creating a new element, the count should be two. This you could test with

     find("#tasks .nested-fields").count.should == 2
    

    Filling in the newly added nested element, you could use the :last-child css selector

     find("#tasks .nested-fields:last-child input#description").set("something")
    

    How names and id are formed, are close to rails internals, so i try to stay away of those.

    0 讨论(0)
  • 2021-01-05 17:55

    Maybe using Capybara finders all, first and the selector input. Something like this:

    visit new_resource_path
    click_link "Add a Nested Resource"
    first("input[name='nested_resource[name]']").set("Nested Resource")
    click_button "submit"
    

    Or

    visit new_resource_path
    click_link "Add a Nested Resource"
    click_link "Add a Nested resource"
    all("input[name='nested_resource[name]']").each do |input|
      input.set("Nested Resource")
    end
    click_button "submit
    

    This is only an approach, I've never worked with cocoon. This is however, a form to test dynamic inputs.

    0 讨论(0)
  • 2021-01-05 18:04

    A possible alternate that I just used is to dynamically update the label of each added form field (using the technique mentioned in https://github.com/nathanvda/cocoon/issues/374) and now my Cucumber/Capybara tests can easily insert text into the different multiple form fields distinguishing them via the different labels they have.

    Full details on what I did in this PR https://github.com/AgileVentures/WebsiteOne/pull/1818

    0 讨论(0)
提交回复
热议问题