【问题标题】:Error in Ruby/RSpec/WebDriver > expected respond to 'has_content?'Ruby/RSpec/WebDriver 中的错误 > 预期响应“has_content?”
【发布时间】:2016-10-05 23:24:45
【问题描述】:

谁能解释这个错误?

我的spec_helper.rb 需要capybararspecselenium-webdriver

我的test_spec.rb 文件包含以下内容:

require_relative 'spec_helper'

@browser = Selenium::WebDriver.for :firefox
@browser.get "http://www.google.com"

describe 'ErrorCheck' do
  it 'should log in to Trialnet' do
    expect(@browser).to have_content('Search')
  end
end

我的错误:

expected  to respond to `has_content?`
./spec/webdriver3_spec.rb:9:in `block (2 levels) in <top (required)>'
-e:1:in `load'
-e:1:in `<main>'

知道为什么这种期望会失败吗?它是否返回一个没有正确语法的布尔值来接受它?

【问题讨论】:

    标签: ruby selenium rspec


    【解决方案1】:

    这是因为@browser 实例变量不适用于it 语句。请注意,您的错误消息没有引用它正在执行期望的对象(即expected to respond to 'has_content?'

    这是一个人为的演示,表明它失败了:

    require 'rspec'
    
    @x = 1
    
    describe 'One' do
      it 'should print 1' do
        expect(@x).to eq 1
      end
    end
    
    Failures:
    
      1) One should print 1
         Failure/Error: expect(@x).to eq 1
    
           expected: 1
                got: nil
    

    并且——通过将实例变量移动到it 语句中以使其可用——示例通过:

    require 'rspec'
    
    describe 'One' do
      it 'should print 1' do
        @x = 1
        expect(@x).to eq 1
      end
    end
    
    1 example, 0 failures
    

    而且——如果你使用let——你可以创建一个可以跨示例共享的记忆变量:

    require 'rspec'
    
    describe 'One' do
    
      let(:x) { 1 }
    
      it 'should print 1' do
        expect(x).to eq 1
      end
    
      it 'should print 2' do
        expect(x+1).to eq 2
      end  
    
    end
    

    根据您的示例代码,您可以使用before 块进行设置,然后使用subject,这可能比let 更合适(注意:下面的sn-p 未经测试,@ 之间的区别987654334@ 和 subject 包含在其他 SO 答案、各种博客文章和 rdoc 中):

    describe 'ErrorCheck' do
    
      before :all do
        @browser = Selenium::WebDriver.for :firefox
        @browser.get "http://www.google.com"
      end
    
      subject(:browser) {@browser}       # or let(:browser) {@browser}
    
      it 'should log in to Trialnet' do
        expect(@browser).to have_content('Search')
      end
    end
    

    【讨论】:

    • 我在这里看到了这个概念。在您的示例中,这是有道理的,因为您将有限整数传递给变量,然后对该变量执行期望。但是,我有点困惑如何将页面的全部内容(我正在检查单词“搜索”的那个)传递给一个变量,然后理论上我会检查那个字符串。
    • 您可以将任何对象传递给let,它不必是文字。
    猜你喜欢
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    相关资源
    最近更新 更多