Rails和minitest / spec </fixture>中的NoMethodError <fixture name =“”>

时间:2015-01-11 03:09:51

标签: ruby-on-rails-4 rails-engines minitest

没有minitest / spec,测试看起来像这样,加载my_engine_customers灯具(一切都很好):

my_engine/test/models/my_engine/customer_test.rb

require 'test_helper'

module MyEngine
  class CustomerTest < ActiveSupport::TestCase

    test "alex is id 5" do
      assert my_engine_customers(:alex).id, 5
    end

  end
end

require 'minitest/autorun'添加到test/test_helper.rb后,然后 转换上述测试:

require 'test_helper'

describe MyEngine::Customer do

  let(:alex) { my_engine_customers(:alex) } # error here (error shown below)

  it "alex is id 5" do
    assert alex.id, 5
  end

end

我收到此错误:

NoMethodError: undefined method `my_engine_customers' for
#<#<Class:0x007fb63e8f09e8>:0x007fb63e81b068>

使用minitest / spec时如何访问灯具?

1 个答案:

答案 0 :(得分:8)

当您使用规范DSL时,您将获得一个Minitest::Spec对象来运行您的测试。但Rails夹具和数据库事务仅在ActiveSupport::TestCase中可用,或者从ActionController::TestCase继承的测试类。所以你需要的是规范DSL使用ActionSupport::TestCase进行测试的方法。

这有两个步骤,第一个ActiveSupport::TestCase需要支持规范DSL。您可以通过向test_helper.rb文件添加以下代码来执行此操作:

class ActiveSupport::TestCase
  # Add spec DSL
  extend Minitest::Spec::DSL
end

(您知道ActiveSupport::TestCase.describe是否存在?如果您计划进行嵌套描述,可能需要在添加规范DSL之前删除该方法。)

其次,您需要告诉规范DSL使用ActiveSupport::TestCase。为此目的,规范DSL添加register_spec_type。因此,还要将以下内容添加到test_helper.rb文件中:

class ActiveSupport::TestCase
  # Use AS::TestCase for the base class when describing a model
  register_spec_type(self) do |desc|
    desc < ActiveRecord::Base if desc.is_a?(Class)
  end
end

这将查看描述的主题,如果它是ActiveRecord模型,它将使用ActiveSupport::TestCase而不是Minitest::Spec来运行测试。

正如您所料,当您尝试将规范DSL用于控制器和其他类型的测试时,还会涉及许多其他陷阱。 IMO最简单的方法是在require "minitest/rails"文件中添加依赖minitest-rails,然后test_helper.rb。 minitest-rails完成所有这些配置,并使过程更加顺畅。 (再次,IMO。)

有关详细信息,请参阅我的blaurgh帖子Adding Minitest Spec in Rails 4。 &LT; /无耻自晋升&GT;

相关问题