Capybara 方法对于 #<ArticleForm:0xb5e98bc> 的 calss 未定义方法“expect”是不可接受的

Capybara method is unacceptable from the calss undefined method `expect' for #<ArticleForm:0xb5e98bc>

尝试从 class 方法调用时,方法“预期”无法访问。但是,从功能 spec.So 调用时它工作正常,基本上最后一个方法 (i_expect_to_see_article_on_home_page) 不起作用。

spec/support/ArticleForm.rb

    require 'rails_helper'

class ArticleForm
  include Capybara::DSL


  def visit_home_page
    visit('/')
    self
  end

  def create_an_article
    click_on('New Article')
    fill_in('Title', with: "My title")
    fill_in('Content', with: "My content")
    click_on('Create Article')
    self
  end

  def i_expect_to_see_article_on_home_page
    visit('/')
    expect(page).to have_text("My title")
    expect(page).to have_text("My content")
    self
  end
end

spec/features/article_spec.rb

 require 'rails_helper'

require_relative '../support/ArticelForm.rb'
feature "home page" do
  article_form = ArticleForm.new

  scenario  "Visit the home page and post an article" do
    article_form.visit_home_page.create_an_article
    article_form.visit_home_page.i_expect_to_see_article_on_home_page
  end
end

我不熟悉你使用的语法,但我相信你需要将它包装成 "it block"。我通常是这样写的:

describe "i_expect_to_see_article_on_home_page" do
  it 'should do something' do
    visit('/')
    expect(page).to have_text("My title")
    expect(page).to have_text("My content")
  end
end

您需要 include RSpec::Matchers 在您的对象中。如果你想使用水豚匹配器,你可能还需要对 Capybara::RSpecMatchers 做同样的事情