Rails4 Minitest |使用共享的可重用对象

时间:2015-04-28 19:50:26

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

当我使用minitest运行rake测试时,我收到以下错误:

$ rake test
DL is deprecated, please use Fiddle
Run options: --seed 55196

# Running:

.EE

Finished in 0.950979s, 3.1546 runs/s, 1.0515 assertions/s.

  1) Error:
CategoryTest#test_invalid_without_name:
NoMethodError: undefined method `name=' for nil:NilClass
    test/models/category_test.rb:14:in `test_invalid_without_name'


  2) Error:
CategoryTest#test_invalid_without_long_name:
NoMethodError: undefined method `name=' for nil:NilClass
    test/models/category_test.rb:19:in `test_invalid_without_long_name'

3 runs, 1 assertions, 0 failures, 2 errors, 0 skips

category_test.rb

require "test_helper"

class CategoryTest < ActiveSupport::TestCase

  def category
    @category = Category.new(name:'Homey')
  end

  def test_valid
    assert category.valid?
  end

  def test_invalid_without_name
    @category.name = nil
    refute @category.valid?
  end

  def test_invalid_without_long_name
    @category.name = "A"
    refute @category.valid?
  end

end

在我的模特中,我有category.rb

class Category < ActiveRecord::Base
    validates :name, presence: true
end

我似乎有一个nil类,即使我在我的类别方法中实例化它。知道发生了什么。我刚刚开始使用Minitest,所以不确定发生了什么。

2 个答案:

答案 0 :(得分:1)

待办事项

def category
  @category ||= Category.new(name:'Homey')
end

然后只使用category而不是@category

以这种方式使用getter将设置实例var,如果它之前不存在或检索现有值

答案 1 :(得分:0)

有很多方法可以解决这个问题,但最直接的方法是将category方法替换为:

def setup @category = Category.new(name:'Homey') end