Search code examples
rspecwatir-webdriverassertions

Rspec and watir-webdriver; assert element not present


I'm using Rspec and watir-webdriver and am struggling to write a passing test so that when an item is deleted on screen, that it is not present--and therefore passes Here is what I'm trying to do:

# this method gets the specific item I want to interact with
def get_item(title)
    foo = @browser.div(:text, title).parent.parent
    return foo
end

# This method looks at an element grid that contains all the items
def item_grid_contents
    grid = @browser.div(:class, 'items-grid')
    return grid
end

When I delete the item, these are a few of the ways I've tried to write my assertion:

expect(get_item(title)).not_to be_present # => fails, unable to locate element
expect(item_grid_contents).not_to include(get_item(title)) # => fails, same error

In this case, I am looking to ensure that the element cannot be located, and should pass. Is there another way to write this so it is considered a pass?


Solution

  • Why not just check if div(:text, title) is present? after all if the outer container (parent) is gone, then so would be the contents (child).

    expect(@browser.div(text: title)).not_to be_present
    

    or (not sure I have my expect syntax right here..)

    expect(@browser.div(text: title).present?.to be_false
    

    small note re ruby.. you can make those methods a little cleaner by not bothering with an intermediate variable. You can in fact even eliminate 'return' as it's implied (but some of us like it for readability) Also most folks writing Ruby code use two space indents. So for your above methods, you could just use

    def get_item(title)
      return @browser.div(:text, title).parent.parent
    end
    

    or even

    def item_grid_contents
      @browser.div(:class, 'items-grid')
    end