Bypassing the database and testing to see if this solution works
chenge
Posted on October 27, 2018
I was thinking about how to not rely on the database in the test a few years ago, but I have not found a viable solution. Seeing this article today, I feel that the proposal proposed by the author seems to be feasible and relatively simple.
How to test that you are creating a record without using the database
I simply verified it, no problem.
I plan to do a real project verification later.
class Product < ActiveRecord::Base
end
store = Product
Catalog.add_product(attrs, store)
This is an example. The advantage of this is that it is more readable, you can simulate the store to avoid database testing.
Hey this is the test code
###
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
In the code, store is used instead of Product, and the store is replaced when testing.
I used the rspec test to be feasible, but the problem is that the verification code is not executed after the simulation, I don't know how to solve it.
Clean Architecture
As shown in the figure, the business model should be centered, the use case organizes the code, and the controller and database should be peripheral interfaces.
I feel that this code is to make the model as the entity, the corresponding Product class and class method as the database interface. Closer to the architectural idea of ββthe illustration. The original rails are organized with data as the center, or the database is the center.
Clean Architecture Description
Look at the code, how do you feel? Please see the original code for the detailed code.
Posted on October 27, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.