Why use yup validation? - react-hook-form

There is a validation method provided by the react hook form. Nevertheless, some developers sometimes use yup validation. What I thought about seems to have the advantage of using schema validation together in the frontend and backend.
I wonder if there is anything else out of this.

I'm using zod as an external validation instead of yup ...
schema validation together in the frontend and backend.
Another big advantage is ...
Since the schema can be defined independently, unit testing can be done easily.
Since the schema can be defined independently, it is easy to understand as a validation definition.
Can handle complex validation
Complex validation is, for example, "when the validation of field A depends on the state of other fields B".
With zod, you can create complex validations across other fields, such as with refine superRefine.
https://github.com/colinhacks/zod#refine
https://github.com/colinhacks/zod#superrefine

Related

Automatically Testing Models in Rails

I just, manually, discovered a migration error. I added a new field to a model, and forgot to add it into the model_params method of the controller. As a result the new field wasn't persisted to the database.
Easy enough to fix once I noticed the problem, but it got me to wondering if there was a way to detect this in testing. I would imagine something like a gem that would parse the schema and generate a set of tests to ensure that all of the fields could be written and that the same data could be read back.
Is this something that can be (or is) done? So far, my searches have led me to lots of interesting reading, but not to a gem like this...
It is possible to write what you would want. Iterate through all the fields in the model, generate params that mirrors those fields, and then run functional tests on your controllers. The problem is that the test is brittle. What if you don't actually want all the fields to be writable through params? What if you reference a model in another controller outside of the standard pattern? How will you handle generating data that would pass different validations? You would either have to be sure that your application would only be written in a certain way or this test would become more and more complex to handle additional edge cases.
I think the solution in testing would be to try to keep things simple; realize that you've made a change to the system and as a result of that change, corresponding tests would need to be updated. In this case, you would update the functional and unit tests affected by that model. If you were strictly adhering to Test Driven Design, you would actually update the tests first to produce a failing test and then implement the change. As a result, hopefully the updated functional test would have failed in this case.
Outside of testing, you may want to look into a linter. In essence, you're asking if you can catch an error where the parameters passed to an object's method doesn't match the signature. This is more catchable when parsing the code completely (i.e. compilation in a static type environment).
EDIT - I skipped a step on the linting, as you would also have to write your code a certain way that a linter would catch it, such as being more explicit of the method and parameters passed to it.
You might want to consider that such a gem may not exist because its not that practical or useful in real life.
Getting the columns off a model is pretty simple from the reflection methods that Active Record gives you. And yeah you could use that theoretically to automagically run a bunch of tests in loop.
But in reality its just not going to cut it. In real life you don't want every column to be assignable. Thats why you are using mass assignment protection in the first place.
And add to that the complexity of the different kinds of constraints and data types your models have. You'll end up with something extremely complex with just adds a bunch of tests with limited value.
If you find yourself omitting a property from mass assignment protection than your should try to cover that part of your controller either with a functional test or an integration test.
class ArticlesControllerTest < ActionController::TestCase
def valid_attributes
{
title: 'How to test like a Rockstar',
content: 'Bla bla bla'
}
end
test "created article should have the correct attributes" do
post :create, article: valid_attributes
article = Article.last
valid_attributes.keys.each do |key|
assert_equals article[key], valid_attributes[key]
end
end
end

RSpec: Shared examples for Validators?

I have several models that have start_time and end_time and I have a custom validator that has special rules for these fields. For testing, I feel like I've got 3 options:
Have a validator and validator_spec. Then re-test the entire implementation of the validators in every model to ensure that the validator is working with that model.
Have a validator and validator_spec. In each model, somehow check that the already-tested validator is being included in a model. (Maybe this means testing one condition that would only arise from the validator being included.)
Creating a shared example as the validator test, and include it in each model's test (although it_behaves_like SomeValidator looks kind of weird)
Any thoughts? The validator has several conditions so I'd find it taxes and not DRY to implement #1.
i would propose another option:
4.) implement a validator_spec and build a custom matcher which can be reused in every model using this validator
maybe you can find some inspiration at https://github.com/thoughtbot/shoulda-matchers
The 'mockist' approach would be to write a spec for the validator class, so that it can be tested in isolation. Then in your model specs, you can stub the validator to return a pre-determined value.
There is a trade-off here: You're avoiding a combinatory increase in the number of tests, so your test suite will smaller, faster, and easier to maintain. But your introducing a small risk that in some situations a model may not work in combination with the real validator once integrated in the production code.

Load model partly in Ruby On rails

guys! I'm trying to make right architecture decision:
I need to hide from user of my site some fields of other users by default. So not to bother with filtering the fields in views I want to not load those fields at all, like:
default_scope -> { select(column_names - FILTERED_PARAMS) }
the rest of fields should be loaded explicitly in special cases.
The problem is that once code refers to the missing fields nomethod error shows up. I tried to meta-program those fields but fruitless this far. It seems to me that this approach doesn't fit to the AR object life-cycle.
Have you ever implemented such functionality if so what pattern have you chosen?
From my experience the best decision would be not to filter these params on the query with select, but to filter what parameters are actually sent to the user. my_model.as_json (with given param filtering options) is a simple solution for that, but for more advanced uses I would advise Rabl gem
https://github.com/nesquena/rabl
That way you have more control over which params are returned even in very advanced cases in a model-view-controller manner.

Rails best practice - handling errors rails

I am new to rails. I want to know the best way to handle inputs errors in rails. Using :message in validates_format_of method then checking in the views the value of the hash or initializing the model with a ActiveModel::Errors.new, and then using it in the views (passing in the model attr_reader :errors), or other any way ?
I use :message invalidates_format_of method then checking in the views, This is a universal practice
The guide http://guides.rubyonrails.org/active_record_validations_callbacks.html#error_messages-and-error_messages_for
A good way to validate input errors is to have both client-side and server-side validations. You can rely on Rails validators on your models, and on the front end you can either use the newer HTML elements, javascript, or a combination of both.
With regards to Rails validations specifically, I don't think you need to stray too far from the conventions. Obviously if you need a different strategy you can definitely incorporate it, but at that point I would definitely suggest adding tests (which is not something I typically do for Rails validations).

Get a list of validation rules in Rails 3?

I need to get a list of validation rules out of a Model in my Rails application. I have searched around and looked through the source of a few client-side validation gems, but am still scratching my head about how to do this. Is there an easy way to just pull a list of validation rules out of a Rails model?
My specific use case is creating an API where the entry form for new items will be auto-generated from the Model definition, and I need to be able to express which fields are required, max length, etc. I already have fields, types, and length from the columns method, but there does not seem to be any type of similar validations method that returns what I need (mainly, required fields as enforced with validates and validates_presence_of, etc.).
Check out the #validators and #validators_on methods:
http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html
You will have to write some custom code that operates on the returned objects and determines which attributes are required, i.e. which ones have validates_presence_of.

Resources