【问题标题】:Can't find field when using symbol reference使用符号引用时找不到字段
【发布时间】:2011-07-15 06:56:56
【问题描述】:

我第一次玩 RoR,遇到了一个奇怪的错误。我的导航链接有以下测试代码:

describe "when logged in" do 
  before(:each) do
    @user = Factory(:user)
    visit login_path

    #the line below is the weird one
    fill_in "session[user_name]", :with => @user.user_name

    fill_in :password, :with => @user.password
    click_button
  end

  it "should have navigation links" do
    response.should have_selector("nav")
  end

  it "should have link to log out" do
    response.should have_selector("a", :href => logout_path, :content => "Log out")      
  end  
end

上面的代码可以正常工作,但是如果我要更改行

fill_in "session[user_name]", :with => @user.user_name

fill_in :user_name, :with => @user.user_name

它不起作用,我不知道为什么。我得到的错误是

Failure/Error: fill_in :user_name, :with => @user.user_name
   Webrat::NotFoundError:
   Could not find field: :user_name

生成的相关html为:

<label for="session_user_name">User name</label><br/>
<input id="session_user_name" name="session[user_name]" size="30" type="text" />
<label for="session_password">Password</label><br/>
<input id="session_password" name="session[password]" size="30" type="password" />

如果您查看您看到的代码,我对密码就是这样做的,而且效果很好。我想使用导致错误的语法,所以我做错了什么吗?

【问题讨论】:

  • 请包含表单的输出 HTML。
  • 查看更新...只添加了html的相关部分。

标签: ruby-on-rails-3 rspec webrat


【解决方案1】:

试试这个:

fill_in "user name", :with => @user.user_name

我认为 webrat 很不错,它能够找到您的标签“密码”,因为它不区分大小写,并将 :password 转换为“密码”。

您也可以使用 HTML id 属性,即

fill_in :session_user_name, :with => @user.user_name

如果您正在考虑改用 Capybara 而不是 Webrat,这里有个问题:Capybara 区分大小写,因此它会在 fill_in "user name" 上失败。

我不确定这里的最佳做法是什么,但我已切换到使用 HTML idname 属性,而不是我自己代码中的标签文本。这样做的原因是它不那么脆弱,因为人们更改网站上面向客户的文本比更改语义元素和名称更多。

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 2016-01-17
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多