首页 > 解决方案 > 如何在测试中运行方法

问题描述

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

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

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

我希望控制台打印“它可以工作”,但它会打印错误:

NoMethodError: undefined method `add_postcodes_from_csv'

标签: ruby-on-railsunit-testingmocha.js

解决方案


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

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

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

其中的关键部分是assert,它基本上是触发测试运行的原因。您是在问“当我这样做时,它会返回 true 吗?”

我会先看这里:https ://guides.rubyonrails.org/testing.html ,以便更好地了解测试最佳实践。


推荐阅读