2012-05-29 33 views
48

我已經發現,當我想將值設置爲文本字段,文本區域或密碼字段時,我可以使用ID,名稱或標籤somethingfill_in something, :with => some_value。但是,當我嘗試將值設置爲<input type="hidden">字段(並且我想這樣做,因爲這些字段通常是我單獨測試的客戶端腳本)時,此方法失敗。我怎麼能用水豚設置這樣一個隱藏的領域?可能嗎?如何填充水豚的隱藏領域?

HTML:

<input id='offer_latitude' name='offer[latitude]' type='hidden'> 
<input id='offer_longitude' name='offer[longitude]' type='hidden'> 

規格:

describe "posting new offer" do 
    it "should add new offer" do 
    visit '/offer/new' 
    fill_in 'offer[latitude]', :with => '11.11' 
    fill_in 'offer[longitude]', :with => '12.12' 
    click_on 'add' 
    end 
end 

給出:

1) posting new offer should add new offer 
    Failure/Error: fill_in 'offer[latitude]', :with => '11.11' 
    Capybara::ElementNotFound: 
    cannot fill in, no text field, text area or password field with id, name, or label 'offer[latitude]' found 
+3

通常一個人不能在一個隱藏字段填寫,所以爲此豚沒有填寫他們看到https://groups.google.com/forum/? fromgroups#!topic/ruby​​-capybara/EstLVItkyrA進行更多討論。但通常你要麼填充它在服務器上或使用JavaScript .. – Doon

+0

@ Doon的評論是非常真實的。如果你想檢查/改變隱藏的輸入,很可能你使用了錯誤的工具。 Capybara旨在在各種情況下測試整個應用程序,而不是測試您的JS組件。結帳[茉莉](http://pivotal.github.com/jasmine/)或[Chai](http://chaijs.com/)。然而,在某些情況下,這是明智的,例如填充在不兼容瀏覽器中填充的HTML5輸入。 Polyfills經常隱藏正確的輸入並插入額外的標記。 – skalee

回答

72

你需要找到隱藏字段,並將其值。有一對夫婦的方式,這可能是最簡單

find(:xpath, "//input[@id='my_hidden_field_id']").set "my value" 

如果你執行在生產client_side腳本,你能告訴豚用一個JavaScript兼容的驅動程序

page.execute_script("$('hidden_field_id').my_function()") 
+0

是的,XPath完成了這項工作。你在@附近有一個錯字,它應該是'find(:xpath,「//input[@id='my_hidden_​​field_id']"".setset」my value「' – skalee

+0

哎呀,修正!謝謝 – DVG

+16

CSS匹配器對我來說工作得很好'find(「#my_hidden_​​field」)。set(「my value」)' – bonyiii

1

運行如果你使用的騷靈/ phantomjs作爲一名司機和jQuery是不工作的你,總是有良好的老式JS:

page.execute_script("document.getElementById('#some-id').value = 'some-value'"); 
+0

僅當您對返回值感興趣時(不是對象),才使用'evaluate_script'。 'execute_script'在這種情況下更好。 – skalee

+0

不錯的答案,但jQuery與poltergeist/phantomjs合作。 –

+2

可能你的id是'some-id',而不是'#some-id'。 – nroose

41

有很多方法來達到同樣的效果。一個我最喜歡的是:

first('input#id.class', visible: false).set("your value") 
+0

first('input#id.class',visible:false).set('your value') –

+0

謝謝。更新了我的回覆。 –

+0

作品謝謝!比xpath解決方案更容易閱讀。 –