如何在测试中使用 运行 方法

How to run method in test

我只是想 运行 在我的测试中使用一个方法,看看它是否有效。

我在测试中尝试了以下代码行 class:

UserPostcodesImport.add_postcodes_from_csv

我的user_postcodes_import_test.rb:

require "test_helper"
require "user_postcodes_import"

class UserPostcodesImportTest < ActiveSupport::TestCase
  it "works" do
    UserPostcodesImport.add_postcodes_from_csv
  end
end

我的user_postcodes_import:

class UserPostcodesImport
  class << self
    def add_postcodes_from_csv
      puts "it works"
    end
  end
end

我希望控制台打印 "it works" 但它打印错误:

NoMethodError: undefined method `add_postcodes_from_csv'

所以测试并不是那样的。在这种情况下您需要做的是查看测试调用并执行类似这样的操作

test "the truth" do
  assert true
end

所以你可能

class UserPostcodesImportTest < ActiveSupport::TestCase
  it "works" do
    test_string = UserPostcodesImport.add_postcodes_from_csv
    assert !test_string.blank?
  end
end

如果您使用的是 rspec,它可能看起来像这样:

class UserPostcodesImportTest < ActiveSupport::TestCase

  {subject = UserPostcodesImport}
  it "works" do
    expect (subject.add_postcodes_from_csv).to_not be_nil
  end
end

类似的东西...在此处检查 rspec 的语法:https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers

其中的关键部分是 assert,这基本上是将测试触发到 运行 的原因。你问的是 "when I do THIS, does it return true?"

我首先查看此处:https://guides.rubyonrails.org/testing.html 以便更好地了解测试最佳实践。