Rails4 最小测试 |使用共享的可重用对象
Rails4 Minitest | using a shared reusable object
当我使用 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 class 即使我在我的类别方法中实例化它。知道发生了什么。我刚刚开始使用 Minitest,所以不确定发生了什么。
做
def category
@category ||= Category.new(name:'Homey')
end
那就只用category
不@category
以这种方式使用 getter 将设置实例变量(如果它之前不存在)或检索现有值
有很多方法可以解决这个问题,但最直接的方法是将 category
方法替换为:
def setup
@category = Category.new(name:'Homey')
end
当我使用 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 class 即使我在我的类别方法中实例化它。知道发生了什么。我刚刚开始使用 Minitest,所以不确定发生了什么。
做
def category
@category ||= Category.new(name:'Homey')
end
那就只用category
不@category
以这种方式使用 getter 将设置实例变量(如果它之前不存在)或检索现有值
有很多方法可以解决这个问题,但最直接的方法是将 category
方法替换为:
def setup
@category = Category.new(name:'Homey')
end