【问题标题】:write unit test for saving data into db编写单元测试以将数据保存到数据库中
【发布时间】:2017-06-27 02:16:57
【问题描述】:
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 任务中,我已将值保存到数据库中,现在我想测试保存的值是否等于我真正发送到数据库的值。该怎么做,或者我做得对吗?

【问题讨论】:

    标签: ruby unit-testing testunit


    【解决方案1】:

    首先,您正在尝试检查已经由行业领先工程师测试过的东西。如果你看到ActiveRecord 项目,每个 API 都经过了严格的测试。所以我建议你跳过这个。

    但是,如果您的目的是学习单元测试,那么您又做错了。单元测试是一种黑盒测试。在您的情况下,您不应该调用/调用任何其他类或第三方软件/服务,例如 Database

    我们称之为集成测试。


    我想测试保存的值是否等于我真正发送到的值 数据库

    很简单;见:

      test "should save tasks" do
        task = FactoryGirl.build(:task, name: 'John')
        task.save
        assert_equal 'John', task.reload.name
      end 
    

    reload 从数据库中获取记录。

    【讨论】:

    • 如果我想测试FactoryGirl.build(:task, name: 'John, finished: 0') 怎么办?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 2016-03-24
    • 2011-09-30
    相关资源
    最近更新 更多