2017-05-25 81 views
1

在Capybara中,我有幾個命令要在共享某個相同父節點的節點上執行,但在少數情況下,我需要引用完全不同的節點。這可以這樣寫:從「內」塊內引用外部節點

find('.the .same #part').find('#different_part1').set... 
find('.the .same #part').find('.different_part2').set... 
find('#a_completely_different_path').set... 
find('.the .same #part').find('#different_part3').set... 
find('.the .same #part').find('.different_part4').set... 

我想用within方法把它們放在一起,但具有完全不同的道路節點,我需要參考的背景下within塊之外。我不知道如何做到這一點:

within('.the .same #part') do 
    find('#different_part1').set... 
    find('.different_part2').set... 
    # find('#a_completely_different_path').set... 
    find('#different_part3').set... 
    find('.different_part4').set... 
end 

我怎麼能暫時從within效果逃跑,並參考?

回答

4

綜觀within源,

def within(*args) 
    new_scope = if args.first.is_a?(Capybara::Node::Base) then args.first else find(*args) end 
    begin 
    scopes.push(new_scope) 
    yield 
    ensure 
    scopes.pop 
    end 
end 

你或許應該能夠將一個方法添加到Session用於反轉的功能,如。

def without 
    current_scope = scopes.pop 
    yield 
ensure 
    scopes.push(current_scope) 
end 

這應該讓你做到以下幾點:

within('.the .same #part') do 
    find('#different_part1').set... 
    find('.different_part2').set... 
    without { find('#a_completely_different_path').set... } 
    find('#different_part3').set... 
    find('.different_part4').set... 
end 
+0

太好了。謝謝。 。 – sawa

+1

你的回答引導我到正確的地方去尋找並提供了很大的幫助,但我想出了一個更簡單的解決方案。對不起,我會將接受的答案移到我的。 – sawa

1

我找到了一種方法來做到這一點。使用page.document

within('.the .same #part') do 
    find('#different_part1').set... 
    find('.different_part2').set... 
    page.document.find('#a_completely_different_path').set... 
    find('#different_part3').set... 
    find('.different_part4').set... 
end 
+0

hm'page.find(..)' - 沒有工作? –

+0

它爲什麼會起作用? – sawa