[英]How to test Rails model associations
Trying to test a module. 尝试测试模块。 It works when executed in rails console, but not when written as a test.
它在Rails控制台中执行时有效,但在作为测试编写时则无效。 Suppose the following:
假设以下内容:
MyModel 为MyModel
a) has_many :my_other_model a)has_many:my_other_model
MyOtherModel MyOtherModel
a) belongs to :my_model a)属于:my_model
Module example: 模块示例:
module MyModule
def self.doit
mine = MyModel.first
mine.my_other_models.create!(attribute: 'Me')
end
end
Now test: 现在测试:
require 'test_helper'
class MyModuleTest < ActiveSupport::TestCase
test "should work" do
assert MyModule.doit
end
end
Returns: 返回:
NoMethodError: NoMethodError: undefined method `my_other_models' for nil:NilClass
Now try the same thing in the console: 现在,在控制台中尝试相同的操作:
rails c
MyModule.doit
Works just fine. 效果很好。 But why not as a test?
但是为什么不做测试呢?
Your test database is empty when you run this test, so calling MyModel.first
is going to return nil
, then you try to chain an unknown method to nil. 运行此测试时,测试数据库为空,因此调用
MyModel.first
将返回nil
,然后尝试将未知方法链接到nil。 What you'll probably want for your test suite is a fixture , which is just sample data. 您可能需要的测试套件是Fixture ,它只是示例数据。 For now, you you can just create the first instance to get the test to work.
现在,您只需创建第一个实例即可使测试生效。
test "should work" do
MyModel.create #assuming the model is not validated
assert MyModule.doit
end
You could also refactor your module. 您也可以重构模块。 Adding
if mine
will only try to create the other models if mine is not nil. 如果我的不为零,则添加
if mine
将仅尝试创建其他模型。 That would get the test to pass, but negates the purpose of your test. 那会使测试通过,但会否定测试的目的。
def self.doit
mine = MyModel.first
mine.my_other_models.create!(attribute: 'Me') if mine
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.