编写单元测试以将数据保存到数据库中
write unit test for saving data into db
require_relative File.expand_path '../../test_helper',__FILE__
FactoryGirl.define do
factory :task do
name "testinga again"
finished 0
end
end
class TaskTest < Test::Unit::TestCase
include FactoryGirl::Syntax::Methods
test "should not save tasks without title" do
task = Task.new
assert_equal false, task.save
end
test "should save tasks" do
task = FactoryGirl.create(:task)
assert_equal attributes_for(:task), task
end
end
我想对任务创建过程进行单元测试。在 should save task
任务中,我已经将值保存到数据库中,现在我想测试保存的值是否等于我真正发送到数据库的值。怎么做或者我做得对吗?
首先,您正在尝试检查已经由行业领先的工程师测试过的东西。如果您看到 ActiveRecord
项目,每个 API 都经过严格测试。所以我建议你跳过这个。
但是,如果您的目的是学习单元测试,那么您又错了。单元测试是一种黑盒测试。您不应该 call/invoke 任何其他 类 或第三方 softwares/services,例如 Database
在您的情况下。
我们称之为集成测试。
I want to test if the saved value is equal to what i really sent to
the db
很简单;见:
test "should save tasks" do
task = FactoryGirl.build(:task, name: 'John')
task.save
assert_equal 'John', task.reload.name
end
reload
从数据库中获取记录。
require_relative File.expand_path '../../test_helper',__FILE__
FactoryGirl.define do
factory :task do
name "testinga again"
finished 0
end
end
class TaskTest < Test::Unit::TestCase
include FactoryGirl::Syntax::Methods
test "should not save tasks without title" do
task = Task.new
assert_equal false, task.save
end
test "should save tasks" do
task = FactoryGirl.create(:task)
assert_equal attributes_for(:task), task
end
end
我想对任务创建过程进行单元测试。在 should save task
任务中,我已经将值保存到数据库中,现在我想测试保存的值是否等于我真正发送到数据库的值。怎么做或者我做得对吗?
首先,您正在尝试检查已经由行业领先的工程师测试过的东西。如果您看到 ActiveRecord
项目,每个 API 都经过严格测试。所以我建议你跳过这个。
但是,如果您的目的是学习单元测试,那么您又错了。单元测试是一种黑盒测试。您不应该 call/invoke 任何其他 类 或第三方 softwares/services,例如 Database
在您的情况下。
我们称之为集成测试。
I want to test if the saved value is equal to what i really sent to the db
很简单;见:
test "should save tasks" do
task = FactoryGirl.build(:task, name: 'John')
task.save
assert_equal 'John', task.reload.name
end
reload
从数据库中获取记录。