首页 > 解决方案 > Rspec,无法在我的类中为 ruby​​ gem 调用方法,错误:ruby NoMethodError:未定义方法 `pull' for Status::Page:Module

问题描述

如何在宝石的 rspec 测试中调用我的主类中的方法?

我见过像这样的其他问题,但没有一个对我有用的答案,所以我问这个问题。

我尝试为正在制作的 gem 编写 rspec 测试(我没有使用 Rails),但我无法调用主文件中的方法:

require "status/page/version"
require 'thor'
require "nokogiri"
require 'open-uri'
require 'date'

module Status
  module Page
    class CLI < Thor
      desc "pull", "query website status"
      def pull
      .....

这就是我在 page_specs.rb 文件中调用的方式:

RSpec.describe Status::Page do
  it "has a version number" do
    expect(Status::Page::VERSION).not_to be nil
  end

  it "does something useful" do
    expect(true).to eq(true)
  end

  it "it should output to a file on pull" do
    msg = Status::Page.pull
    expect(msg).not_to be nil
  end

end

有人可以建议我应该如何在我的情况下调用 Rspec 中的方法吗?

谢谢

标签: rubyrspec

解决方案


尝试Status::Page::CLI.new.pull

pull是类的一个实例方法Status::Page::CLI,因为它是一个实例方法,所以你需要用.new.

由于该类继承自 Thor,因此调用.new确实会通过Thor::Base.initialize。但是从文档来看,似乎为所有参数设置了默认值,所以只调用.new不带参数就足够了。


推荐阅读