Capybara :: ElementNotFound,但它在那里

问题描述 投票:3回答:4

我遇到以下错误:

Capybara::ElementNotFound: Unable to find field "username"
./spec/controllers/sessions_controller_spec.rb:10:in `block (3 levels) in <top (required)>'

spec:

require 'spec_helper'

describe SessionsController do
  before :each do
    @user = FactoryGirl.create(:user)
  end
  context 'creating a new session' do
    it 'can set the current_user variable to the logged user' do
      visit '/login'
      fill_in 'username', with: 'gabrielhilal' #I have tried `Username` as well
      fill_in 'password', with: 'secret'
      click_button 'Login'
      current_user.should == @user
      current_user.username.should == 'gabrielhilal'
    end
  end
  context 'destroying existing session' do
    xit 'can destroy the current_user' do
    end
  end
end

但是我的表单中有字段username

<form accept-charset="UTF-8" action="/sessions" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" / <input name="authenticity_token" type="hidden" value="x7ORLDIvq1BXr8SOkd/Zla9Pl5R5tBXAtyflCpTGCtY=" /></div>
  <div class="field">
    <label for="username">Username</label>
    <input id="username" name="username" type="text" />
  </div>
  <div class="field">
    <label for="password">Password</label>
    <input id="password" name="password" type="password" />
  </div>
  <div class="actions">
    <input name="commit" type="submit" value="Login" />
  </div>
</form>

我对cucumber做了类似的测试,并且通过了,这确认了字段username在那里:When to switch from cucumber to rspec in the BDD cycle for a login procedure

任何想法?

EDIT-我添加了save_and_open_page,这给了我空白页。 puts "#{page.html.inspect}"还返回强度。

""

Capybara::ElementNotFound: Unable to find field "username"
./spec/controllers/sessions_controller_spec.rb:12:in `block (3 levels) in <top (required)>'
ruby-on-rails rspec capybara bdd ruby-on-rails-4
4个回答
6
投票
我知道您已经回答了自己的问题(种类),但是我仍然有必要让您知道您提供的示例是控制器和请求规范的组合...

引用RSpec - Controller Specs的逐字记录:Note: To encourage more isolated testing, views are not rendered by default in controller specs.

主要区别(RSpec解释它是哪种规格的方式)是一行:describe SessionsController do

使其与RSpec和测试最佳实践保持一致:

    将规格移至spec/requests
  1. 将描述更改为describe "SessionsController" do
  2. 删除render_views
  • 您的规格应该可以正常运行...

    请查看RSpec - Request Specs以了解我的意思。我还将检查betterspecs.org,以了解可以改进测试的方式。


  • 8
    投票
    您可以使用以下终端进行调试:

    it {puts page.body}

    然后查看是否有“用户名”输入。但是我认为第一步visit '/login'上的问题

    0
    投票
    我意识到我必须明确地告诉控制器渲染视图。我在rspec readme中找到了它,所以我解决了添加render_views的问题。

    describe SessionsController do render_views #this line solved the problem before :each do user = FactoryGirl.create(:user) end ...


    0
    投票
    就我而言,只需删除block_unknow_urls中的features/support/env.rb

    Capybara::Webkit.configure do |config| config.allow_unknown_urls end

    © www.soinside.com 2019 - 2024. All rights reserved.