shoulda-matcher error validating length_of - activerecord

I'm writing some specs for my User model but the tests are not passing. I'm fallowing this from the github page of the gem without success. This is my code:
validates :phone, numericality: { only_integer: true }, allow_blank: true, length: { is: 7 }
validates :mobile, numericality: { only_integer: true }, allow_blank: true, length: { is: 10 }
and my specs
it { should ensure_length_of(:phone).is_equal_to(7) }
it { should ensure_length_of(:mobile).is_equal_to(10) }
This validations should only run during the update process.
The errors:
Did not expect errors to include "longitud errónea (debe ser de 7 caracteres)" when telefono is set to "xxxxxxx", got error: longitud errónea (debe ser
de 7 caracteres)
Did not expect errors to include "longitud errónea (debe ser de 10 caracteres)" when celular is set to "xxxxxxxxxx", got error: longitud errónea (debe s
er de 10 caracteres)
FYI: I've set Spanish Locales; I think this is the cause
Hope someone could help me. Thanks is advance

I think you got the error because shoulda_matcher does not expect that length: { is: 7 } is used with numericality.
PS as for me - it is strange to use numeric for phone numbers, you can use string and use validates with format to be sure in validness data. For example email validation here

Related

Ruby aws device farm throwing argument error when calling schedule_run method

I'm trying to schedule a run using the aws device farm sdk, I have followed the documentation, however, every time I call the schedule_run method I get this error:
Aws::DeviceFarm::Errors::ArgumentException: Missing or unprocessed resources
This is the method from where I'm calling schedule_run:
def schedule_run
aws_client.schedule_run({
project_arn: ANDROID_PROJECT_ARN, # required
app_arn: get_uploads_by_name(ANDROID_APP, 'ANDROID_APP').arn,
device_pool_arn: get_device_pool_by_name('Android test decive pool').arn,
device_selection_configuration: nil,
name: "test_run",
test: { # required
type: "APPIUM_RUBY",
test_package_arn: get_uploads_by_name(TEST_SUITE, 'APPIUM_RUBY_TEST_PACKAGE').arn,
test_spec_arn: get_uploads_by_name('aws_android_4.yml', 'APPIUM_RUBY_TEST_SPEC').arn,
filter: nil,
parameters: nil
},
configuration: {
extra_data_package_arn: nil,
network_profile_arn: get_network_profile_by_name('Full').arn,
locale: "en_US",
location: {
latitude: 47.6204, # required
longitude: 122.3491 # required
},
vpce_configuration_arns: nil,
customer_artifact_paths: {
ios_paths: nil,
android_paths: nil,
device_host_paths: %w[/tmp/allure-results /tmp/screenshots]
},
radios: {
wifi: true,
bluetooth: false,
nfc: true,
gps: true
},
auxiliary_apps: nil,
billing_method: "UNMETERED" # accepts METERED, UNMETERED
},
execution_configuration: {
job_timeout_minutes: 150,
accounts_cleanup: false,
app_packages_cleanup: false,
video_capture: false,
skip_app_resign: false
}
})
end
The exception Missing or unprocessed resources typically means that there was an issue with one of your uploads. Use the GetUpload on of your uploads to see what went wrong.

shoulda matcher and conditional validation errors

Here I use the attribute :new_record to set the condition for validation.
attr_accessor :new_record
validates :email, presence: true, email: true, unless: :new_record?
def new_record?
#new_record || true
end
if the new_record? == true, the email validation will be skipped and new user is valid.
I wrote this test:
it { expect(subject).to validate_presence_of(:email) }
and it returns error:
Failure/Error: it { expect(subject).to validate_presence_of(:email) }
User did not properly validate that :email cannot be empty/falsy.
After setting :email to ‹nil›, the matcher expected the User to be
invalid, but it was valid instead.
Note that this test run perfectly if there is no condition added to the validation. Also, the code work well in production.
I also have tried
before(:each) do
subject.new_record = true
end
or
`before { allow(subject).to receive(:new_record?).and_return(true) }`
Can any one help?

Michael Hartl's Rails 5 tutorial chapter 10, listing 10.56, test if the admin attribute is forbidden

I was trying to pass the exercise in listing 10.56 and test if the admin attribute is forbidden.
I added admin parameter in
app/controllers/users_controller.rb
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation,
:admin)
end
also, filled necessary parts in
test/controllers/users_controller_test.rb
test "should not allow the admin attribute to be edited via the web" do
log_in_as(#other_user)
assert_not #other_user.admin?
patch :update, id: #other_user, user: { password: "",
password_confirmation: "",
admin: true }
assert_not #other_user.reload.admin?
end
Still, I am getting unknown error after test:
ERROR["test_should_not_allow_the_admin_attribute_to_be_edited_via_the_web", UsersControllerTest, 3.2600422599352896]
test_should_not_allow_the_admin_attribute_to_be_edited_via_the_web#UsersControllerTest (3.26s)
URI::InvalidURIError: URI::InvalidURIError: bad URI(is not URI?): http://www.example.com:80update
test/controllers/users_controller_test.rb:37:in `block in <class:UsersControllerTest>'
Anyone here was dealing with the same problem?
This error is intended. As the exercise says you added :admin to permitted params before.
Your test now will send the patch request and set admin: true for #other_user (which is possible here, since you added :admin to permitted params). After that you use "assert_not" which will raise the error, since the test expects that
#other_user.reload.admin?
will be false but in your case its true. Deleting :admin from permitted params in app/controllers/users_controller.rb will change your test to green.
The following should give you a non-erroring test that will fail when you allow admin to be altered as you have.
test "should not allow the admin attribute to be edited via the web" do
log_in_as(#other_user)
assert_not #other_user.admin?
patch user(#other_user), params: {
user: { password: "",
password_confirmation: "",
admin: true }
assert_not #other_user.reload.admin?
end

Ruby Grape: Custom validation error message

How do you change the default error messages given by Grape on Validation Errors?
For Example -
params do
requires :email, allow_blank: false
end
If I don't pass the :email in the API call, grape will give error message as ['email is missing', 'email is empty'] but I want to override the message as ['Oops! Email is required.']
So, how can I override the default error messages for Grape default Validation Rules.
format :json
subject.rescue_from Grape::Exceptions::ValidationErrors do |e|
error!({ messages: e.full_messages.map { |msg| "Oops!" + msg }}, 400)
end
Update:
If you want to customize the complete message you can manually edit the grape locale file and override it in your application.
Grape locale en.yml
It seems like the original answer is plain wrong:
https://github.com/ruby-grape/grape#custom-validation-messages
Which should work something like this for OP's example:
params do
requires :email, allow_blank: { false, message: '' }, message 'Oops! Email is required.'
end
The tricky part is that OP is violating 2 validations but wants to have one message. Maybe the workaround above will work, though.

Trouble getting Ember Validations to work

Since Ember doesn't support form validation out of the box (as of this writing anyway), I am looking for a way to validate forms. I came across Dockyards ember-validations and the consensus seems to be that this is the goto module for form validation in EmberJS.
I'm trying to get it to work, but I'm having some trouble getting started.
I'm not using Ember CLI as referenced in the docs, so I have downloaded a compiled ember-validations.js from http://builds.dockyard.com/ and have included ember-validations.js in my apps js file.
The docs now say to pass the validations.mixin into a controller:
So I'm using:
App.MemberaddController = App.FamilyController.extend(EmberValidations.Mixin,{
needs: ["family","notifications"],
familyController: Em.computed.alias('controllers.family'),
notifications: Em.computed.alias('controllers.notifications'),
validations: {
firstname: {
presence: true,
presence : {message: 'mag niet leeg zijn'}
}
},
init: function() {
this.set('familyController.pageTitle', "Gezinslid toevoegen");
},
<etc...>
}
However in the browser I'm seeing
Uncaught ReferenceError: EmberValidations is not defined
Looking at the ember-validations.js I can see the mixin file being referenced as Ember.Validations.Mixin.
So when I pass that to my controller, like
App.MemberaddController = App.FamilyController.extend(Ember.Validations.Mixin,{
I'm seeing:
Error while processing route: memberadd Cannot read property 'invoke' of undefined TypeError: Cannot read property 'invoke' of undefined
In the ember-validations.js file at the _validate function.
What am I doing wrong here?
First on the off chance this is a new project and you have the option to use ember-cli I recommend you do so, the community is moving in that direction.
That said I think your bug is in here
validations: {
firstname: {
presence: true, <-- uneeded
presence <-- remove this space: {message: 'mag niet leeg zijn'}
}
},
should look like this
validations: {
firstname: {
presence: {message: 'mag niet leeg zijn'}
}
},

Resources