2012-05-29 34 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解决方案更容易阅读。 –