Rails 绕过数据库做测试看看这个方案可行么?

chenge · October 26, 2018 · 936 hits

大概几年前我就在思考如何在测试中不依赖数据库,但是一直没有找到可行的方案。今天看到这个文章,感觉作者提出的方案似乎是可行的,而且比较简单。 How to test that you are creating a record without using the database

我简单验证了一下,没有问题。

后续我打算做个实际项目验证一下。

class Product < ActiveRecord::Base
end

store = Product

Catalog.add_product(attrs, store)

这个是一个例子。这样的好处是可读性好一些,可以模拟 store 来避开数据库测试。

👇这个是测试代码


###
class DummyProductsStore
  def self.create(attrs)
  end
end

def store
  DummyProductsStore
end

###

it "creates a record" do
  attrs = { name: "P1", description: "Super Product" }

  # This is the code that expects "store.create(attrs)"  to be called
  expect(store).to receive(:create).with(attrs)

  Catalog.add_product(attrs, store)
end

代码中用 store 代替 Product,测试的时候替换掉 store。

我用 rspec 试验是可行的,不过遇到个问题就是模拟后验证代码没有执行,不知道如何解决。

Clean Architecture

如图,业务模型应该居于中心,用例组织代码,控制器和数据库应该是外围接口。 感觉这个代码是让 model 作为 entity,对应的 Product 类和类方法作为数据库接口。比较接近图示的架构思路。原来的 rails 是以数据为中心来组织的,或者说是数据库为中心。

Clean 架构说明

大家看看代码,觉得如何?详细代码请看原文。

No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.