ruby-on-rails - 如何在测试中运行方法
问题描述
我只是想在我的测试中运行一个方法,看看它是否有效。
我在测试类中尝试了以下代码行:
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'
解决方案
所以测试并不是真的那样工作。在这种情况下,您需要做的是查看测试调用并执行类似的操作
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 ,以便更好地了解测试最佳实践。
推荐阅读
- mysql - 带光标的事件不起作用
- javascript - 如何在java脚本中获取嵌套json的键名和长度
- ios - 使用 UIRefreshControl 刷新 UITableView
- perl - perl 的 Docker 基础镜像;E: 包 'libssl1.0.0' 没有安装候选
- node.js - 如何将nodejs ecdh公钥编码为pem
- android - 将 compileSdkVersion 更改为 android-P 后,Apk 不起作用
- python - 空元组作为python中的exception的参数
- javascript - Javascript代码在桌面和调整大小的窗口上完美运行,但在移动设备上却不行
- python - 列表引用 - 内存 // PYTHON
- java - 从方法的返回值返回数组的索引