Can't find field when using symbol reference
I'm playing around with RoR for the first time and hit a weird error. I have the following test code for my navigation links:
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
the code above works just fine, but if I would change the line
fill_in "session[user_name]", :with => @user.user_name
to
fill_in :user_name, :with => @user.user_name
it won't work and I can't figure out why. The error I get is
Failure/Error: fill_in :user_name, :with => @user.user_name
Webrat::NotFoundError:
Could not find field: :user_name
The relevant generated html is:
<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_passw开发者_开发知识库ord">Password</label><br/>
<input id="session_password" name="session[password]" size="30" type="password" />
If you look at the code you see I do exactly that for the password, and that works just fine. I would like to use the syntax which is causing the error so am I doing something wrong?
Try this:
fill_in "user name", :with => @user.user_name
I think webrat is being nice, and its able to find your label 'Password' because it is case insensitive and its turning :password
into 'Password'.
You could also use the HTML id
attribute, i.e.
fill_in :session_user_name, :with => @user.user_name
One gotcha here is if you are thinking of switching to use Capybara rather than Webrat: Capybara is case-sensitive, so it would fail on fill_in "user name"
.
I'm not sure what the best practice is here, but I have switched to using the HTML id
and name
attributes rather than the label text in my own code. The reason for this is that it is less brittle because people change the customer-facing text on the site more than they change the semantic elements and names.
精彩评论