我发现自己最近这么做了......我怎样才能改进回形针夹具的声明? (对不起,我知道了noob问题)
class ProjectTest < ActiveSupport::TestCase
def xxx
project = Project.new({
:name => 'xxx',
:attachment => File.new(Rails.root + 'test/fixtures/files/attachments/xxx.psd')
})
project.save
project
end
test "should not save project without name" do
assert xxx, "Saved project without a name"
end
test "should save a project with an attachment and have a valid directory" do
assert File.directory?(xxx.directory), "Saved project without establishing a valid directory"
end
test "should save a project with an attachment and have a URL" do
assert !xxx.filename.nil?, "Saved project without establishing a valid URL"
end
test "should save a project with an attachment and have a valid absolute file path" do
assert File.exists?(xxx.absolute_filename), "Saved project without establishing a valid absolute filename"
end
test "should save a project with an attachment and have a valid base filename" do
assert !xxx.base_filename.nil?, "Saved project without establishing a valid base filename"
end
end
答案 0 :(得分:2)
认识到对此的答案是主观的,并且在很大程度上取决于系统的其他部分,这里有一些我希望有价值的想法:
1 - 如果您的灯具使用文件系统太多,请查看FakeFS gem:https://github.com/defunkt/fakefs
2 - 虽然在某些情况下,在与测试本身相同的文件中创建夹具是完全合理的,但我发现希望它们分开更常见的情况。这样可以重用 - 无论是对于其他测试,还是在系统发展过程中与其他数据建立关系。显然取决于你,只需要考虑一下。
答案 1 :(得分:0)
在rails中使用fixture的经典方法是创建一个yaml fixture文件,如下所示:
record1:
name: xxxx
attachment: test/fixtures/files/attachements/xxx.psd
record2:
.... etc.
将其存储在test / fixtures / projects.yml
中然后在测试的顶部,写下:
fixtures:projects
这会将你的灯具文件中的灯具加载到数据库中,此时你可以进行任何你想要的测试。
答案 2 :(得分:0)
另请参阅FactoryGirl或Machinist等解决方案 - 夹具替换,它允许您使用Ruby DSL为测试实体定义工厂。