Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 4 微型测试-Rails 4中的测试类_Ruby On Rails 4_Minitest - Fatal编程技术网

Ruby on rails 4 微型测试-Rails 4中的测试类

Ruby on rails 4 微型测试-Rails 4中的测试类,ruby-on-rails-4,minitest,Ruby On Rails 4,Minitest,我正在尝试在新的Rails 4安装中使用Minitest。我的理解是,如果我有一个不是从ActiveRecord继承的类,那么我应该能够使用Minitest本身,而不需要Rails集成: #test/models/blog.rb require "minitest/autorun" class Blog < Minitest::Unit::TestCase def setup @b = Blog.new end def test_entries assert_empty "me

我正在尝试在新的Rails 4安装中使用Minitest。我的理解是,如果我有一个不是从ActiveRecord继承的类,那么我应该能够使用Minitest本身,而不需要Rails集成:

#test/models/blog.rb
require "minitest/autorun"
class Blog < Minitest::Unit::TestCase

def setup
  @b = Blog.new
end

def test_entries
  assert_empty "message", @b.entries
end

#app/models/blog.rb
class Blog
  attr_reader :entries
  def initialize
   @entries = []
  end
#test/models/blog.rb
需要“微型测试/自动运行”
类Blog
我使用
ruby测试/models/blog.rb
运行测试。
我的问题来自设置方法。如果我没有为我的博客添加条目,测试将失败,并显示一条消息,即安装程序中的参数数量错误。如果我在我的设置消息
@b=Blog.new entries:“Twilight”
中包含一个条目,我的测试将在
test\u entries
方法中失败,因为条目是一个未定义的方法。

您有几个问题。首先,您不需要“test_helper”,这意味着运行此测试时rails没有加载,这意味着rails用于解析缺失常量的机制没有加载。您将需要帮助者或直接需要blog文件。其次,您正在用测试覆盖要测试的常量,这就是为什么您会收到令人困惑的消息。将测试类命名为
BlogTest
,以避免出现这种情况

这就是我认为您正在尝试的:

require "minitest/autorun"
require "models/blog" # Assuming "app" is in your load path when running the test
#require "test_helper" # Or require this instead if you need to use DB

class BlogTest < Minitest::Unit::TestCase

  def setup
    @b = Blog.new
  end

  def test_entries
    assert_empty @b.entries, "Blog entries should be empty"
  end

end
要求“小型测试/自动运行”
需要“models/blog”#假设运行测试时“app”在您的加载路径中
#需要“test_helper”#或者如果需要使用DB,则需要此选项
类BlogTest
这就解决了问题。我不知道如何将“app”添加到我的加载路径,所以我使用了
require\u relative'../../app/models/blog'
。我遵循Avdi的ObjectsOnRails,它一开始避免任何Rails集成来设置和运行测试,这就是为什么我现在试图避免需要“test\u helper”,同时运行
rake test