水豚:元素找不到,但它就在那里



我得到以下错误:

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

规格:

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在那里:在登录过程的BDD周期中,何时从cucumber切换到rspec

知道吗?

编辑-我添加了save_and_open_page,这给了我一个空白页。puts "#{page.html.inspect}"也返回empity。

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

您可以使用以下终端进行调试:

it {puts page.body}

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

我知道您已经回答了自己的问题(有点),但我觉得仍然有必要让您知道,您提供的示例是控制器和请求规范的混合

逐字引用RSpec-控制器规范:Note: To encourage more isolated testing, views are not rendered by default in controller specs.

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

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

  1. 将规范移动到spec/requests
  2. 将描述更改为describe "SessionsController" do
  3. 删除render_views

你的规范应该运行得很好。。。

查看RSpec-请求规范,了解我的意思。我还想看看betterspecs.org,了解如何改进测试。

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

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

在我的情况下,只需在features/support/env.rb:中删除block_unknow_urls

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

相关内容

最新更新