shoulda validate_inclusion_of not working - ruby-on-rails-4

Recently upgraded a codebase to rails4 along with gems, now we're getting this error.
Failure/Error: it { is_expected.to ensure_inclusion_of(:usage).in_array(['Index', 'Slide', 'Body']).with_message("%{value} is not a valid usage") }
["Index", "Slide", "Body"] doesn't match array in validation
and here is the related model code
USAGES = ['Index', 'Slide', 'Body']
validates_inclusion_of :usage, :in => USAGES, :message => "%{value} is not a valid usage"
Is there something I'm missing? I don't understand why this is failing.

validate_inclusion_of uses allow_value internally. Admittedly, we should give you a better error message as to what's going on here, but you should be able to write the following tests to figure out what's happening:
it { should allow_value("Index").for(:usage) }
it { should allow_value("Slide").for(:usage) }
it { should allow_value("Body").for(:usage) }
it do
should_not allow_value("something else").
for(:usage).
with_message("%{value} is not a valid usage")
end
My guess is that shoulda-matchers isn't automatically interpolating the %{value} inside of your failure message. If this is true, then what I would do (after filing an issue) is extract the message to an i18n key, and then pass the name of the key to with_message instead.

worked for me -
expect { should validate_inclusion_of(:usage).in?(['a', 'b']) }

should try this -
validates :usage, inclusion: { :in => %w( Index Slide Body ), :message => "%{value} is not a valid usage" }

Related

Elixir: ExAws: DynamoDB: query-filter

I'm using the library https://github.com/ex-aws/ex_aws_dynamo, and I'm having issues getting a working example of query-filter to work with query. I was hoping someone here has an example they could share.
Here's what I've tried, but it returns an error:
[
key_condition_expression: "highlight_request_id = :highlight_request_id",
expression_attribute_values: [
highlight_request_id: "c692e65e-618f-45a3-ac12-d8103e6444c8"
],
query_filter: %{
range_id: %{
attribute_value_list: ["9990-ORGANIZATION-Pampers"],
comparison_operator: "EQ"
}
}
]
and the error I get back:
{:error,
{"ValidationException",
"1 validation error detected: Value null at 'queryFilter.range_id.member.comparisonOperator' failed to satisfy constraint: Member must not be null"}}
I'm not sure what is considered to be null. Any thoughts?
Make sure your query is written like so (adapted from the ex_aws_dynamo tests):
ExAws.Dynamo.query("person", [
index_name: "email",
key_condition_expression: "#email = :email",
expression_attribute_names: %{"#email" => "email"},
expression_attribute_values: [email: "person#test.com", last_name: "Person"],
filter_expression: "last_name = :last_name"
]) |> ExAws.request()
I was able to run this successfully against my local table, you'll have to fill in the appropriate values for your model. In particular, you'll want to include the index_name, and use the filter_expression, rather than query_filter.
In your case, I believe you'd want something like
ExAws.Dynamo.query("person", [
index_name: "highlight_request_id", # assuming that's the name of the index
key_condition_expression: "#highlight_request_id = :highlight_request_id",
expression_attribute_names: %{"#highlight_request_id" => "highlight_request_id"},
expression_attribute_values: [highlight_request_id: "c692e65e-618f-45a3-ac12-d8103e6444c8", range_id: "9990-ORGANIZATION-Pampers"],
filter_expression: "range_id = :range_id"
]) |> ExAws.request()
Let me know if this gets you any closer - again, worked for me, using the latest version of ex_aws_dynamo (2.2.2, at the moment).

Qunit assert throws not working

I am trying to assert that a few steps in the code (visiting page, providing wrong card-number, password combination and clicking submit)should generate an error from the backend service - I have referred to this already..
and tried the suggestion of using Error Object as the second argument to assert.throws but that doesn't work for me.
i did see this link as well before posting my question,
My problem is - I don't have control over the code that throws the exception/error in this case. (I cannot change it to say Ember.assert etc) I just want to be able to catch an erroneous case.
Secondly, I don't have a component in this case. Its a straight forward API call that's made when click on submit is done, basically an action submitAuthForm is called in controller which calls ember cli mirage scenario that returns the following object problems object.
return new Response(401,{'X-Auth-Token': 'wrong-username-password-combination'},failResponse401);
and the returned object looks like
var failResponse401 = {
problems: [ {
field: null,
index: null,
value: null,
code: '0006',
subCode: '',
details: {},
_type: 'error'
} ]
};
We have a node_module dependency on an in-house exceptions kit that throws an Error object based on this.
Here's my Qunit test
test('ERROR_CASE_visiting /signon, provide cardNumber(2342314) and ' +
'password, submit and expect to see invalid cardnumber/password error',
function (assert) {
assert.expect(2);
assert.throws(
function () {
visit('/signon');
fillIn('#a8n-signon-card-number input', '2342314');
fillIn('#a8n-signon-password input', 'password');
click('#a8n-signon-submit-button button');
},
Error,
"Error Thrown"
);
});
I keep getting this error from Qunit
Error Thrown# 110 ms
Expected:
function Error( a ){
[code]
}
Result:
undefined
Diff:
function Error( a ){
[code]
}defined
Source:
at Object.<anonymous> (http://localhost:7357/assets/tests.js:175:12)
at runTest (http://localhost:7357/assets/test-support.js:3884:30)
at Test.run (http://localhost:7357/assets/test-support.js:3870:6)
at http://localhost:7357/assets/test-support.js:4076:12
at Object.advance (http://localhost:7357/assets/test-support.js:3529:26)
at begin (http://localhost:7357/assets/test-support.js:5341:20)
API rejected the request because of : []# 1634 ms
Expected:
true
Result:
false
Source:
Error: API rejected the request because of : []
at Class.init (http://localhost:7357/assets/vendor.js:172237:14)
at Class.superWrapper [as init] (http://localhost:7357/assets/vendor.js:55946:22)
at new Class (http://localhost:7357/assets/vendor.js:51657:19)
at Function._ClassMixinProps.create (http://localhost:7357/assets/vendor.js:51849:12)
at Function.createException (http://localhost:7357/assets/vendor.js:172664:16)
at Class.<anonymous> (http://localhost:7357/assets/vendor.js:133592:72)
at ComputedPropertyPrototype.get (http://localhost:7357/assets/vendor.js:32450:27)
at Object.get (http://localhost:7357/assets/vendor.js:37456:19)
at Class.get (http://localhost:7357/assets/vendor.js:50194:26)
at http://localhost:7357/assets/vendor.js:133645:30
Is there anything else that i can try to get it to work.
Is there someway i could somehow pass this test, by wrapping the returned response somehow in a way that it doesn't break my test altogether.
I found a workaround following this link
the user pablobm has posted a link to a helper
I used that to workaround this Qunit issue.

Getting uninitialized constant Twilio::REST::RequestError

I keep getting the same error since I upgraded to:
gem 'twilio-ruby', '~> 5.0.0.rc4'
The call was successful set to Twilio, but the getting some error.
app/controllers/home_controller.rb:59:in `rescue in call'
require "rubygems"
require "twilio-ruby"
def call
#twilio = Twilio::REST::Client.new account_sid, auth_token
begin
#call = #twilio.account.calls.create({
:to => ,
:from => twilio_number,
:url => url,
:method => "GET",
:if_machine => "Hangup",
:timeout => "20"
})
# Getting current call status (seems like error here...!)
get_status(#call.sid)
rescue Twilio::REST::RequestError => error
#err_msg = error.message
puts #err_msg
#returned error is like below:
#NameError (uninitialized constant Twilio::REST::RequestError)
end
end
Code for getting current call status:
def get_status(sid)
#twilio = Twilio::REST::Client.new account_sid, auth_token
#call = #twilio.account.calls.get(sid)
puts "Process Status : " + #call.status
return #call.status
end
Please help to figure it out.
Thank you!
For version 5, Try Twilio::REST::RestError.
This is documented here:
There are new classes to rescue errors from. The new library now uses the Twilio::REST::RestError class.

Logstash can not handle multiple heterogeneous inputs

Let's say you have 2 very different types of logs such as FORTINET and NetASQ logs and you want:
grok FORTINET using a regex, ang grok NETASQ using an other regex.
I know that with "type"in the input file and "condition" in the filter we can resolve this problem.
So I used this confing file to do it :
input {
file {
type => "FORTINET"
path => "/fortinet/*.log"
sincedb_path=>"/logstash-autre_version/var/.sincedb"
start_position => 'beginning'
}
file {
type => "NETASQ"
path => "/home/netasq/*.log"
}
}
filter {
if [type] == "FORTINET" {
grok {
patterns_dir => "/logstash-autre_version/patterns"
match => [
"message" , "%{FORTINET}"
]
tag_on_failure => [ "failure_grok_exemple" ]
break_on_match => false
}
}
if [type] == "NETASQ" {
# .......
}
}
output {
elasticsearch {
cluster => "logstash"
}
}
And i'm getting this error :
Got error to send bulk of actions: no method 'type' for arguments(org.jruby.RubyArray) on Java::OrgElasticsearchActionIndex::IndexRequest {:level=>:error}
But if don't use "type" and i grok only FORTINET logs it wroks.
What should i do ?
I'm not sure about this but maybe it helps:
I have the same error and I think that it is caused by the use of these if statements:
if [type] == "FORTINET"
your type field is compared to "FORTINET" but this is maybe not possible because "FORTINET" is a string and type isn't. Some times by setting a type to an input, if there is already a type, the type isn't replaced, but the new type is added to a list with the old type. You should have a look to your data in kibana (or wherever) and try to find something like this:
\"type\":[\"FORTINET\",\"some-other-type\"]
maybe also without all those \" .
If you find something like this try not to set the type of your input explicitly and compare the type in your if-statement to the some-other-type you have found.
Hope this works (I'm working with more complex inputs/forwarders and for me it doesn't, but it is worth a try)

What's the standard pattern for ember-data validations? (invalid state, becameInvalid...)

I've kinda been struggling with this for some time; let's see if somebody can help me out.
Although it's not explicitly said in the Readme, ember-data provides somewhat validations support. You can see that on some parts of the code and documentation:
https://github.com/emberjs/data/blob/master/packages/ember-data/lib/system/model/states.js#L411
https://github.com/emberjs/data/blob/master/packages/ember-data/lib/system/model/states.js#L529
The REST adapter doesn't add validations support on itself, but I found out that if I add something like this in the ajax calls, I can put the model on a "invalid" state with the errors object that came from the server side:
error: function(xhr){
var data = Ember.$.parseJSON(xhr.responseText);
store.recordWasInvalid(record, data.errors);
}
So I can easily to the following:
var transaction = App.store.transaction();
var record = transaction.createRecord(App.Post);
record.set('someProperty', 'invalid value');
transaction.commit()
// This makes the validation fail
record.set('someProperty', 'a valid value');
transaction.commit();
// This doesn't trigger the commit again.
The thing is: As you see, transactions don't try to recommit. This is explained here and here.
So the thing is: If I can't reuse a commit, how should I handle this? I kinda suspect that has something to do to the fact I'm asyncronously putting the model to the invalid state - by reading the documentation, it seems like is something meant for client-side validations. In this case, how should I use them?
I have a pending pull request that should fix this
https://github.com/emberjs/data/pull/539
I tried Javier's answer, but I get "Invalid Path" when doing any record.set(...) with the record in invalid state. What I found worked was:
// with the record in invalid state
record.send('becameValid');
record.set('someProperty', 'a valid value');
App.store.commit();
Alternatively, it seems that if I call record.get(...) first then subsequent record.set(...) calls work. This is probably a bug. But the above work-around will work in general for being able to re-commit the same record even without changing any properties. (Of course, if the properties are still invalid it will just fail again.)
this may seem to be an overly simple answer, but why not create a new transaction and add the pre-existing record to it? i'm also trying to figure out an error handling approach.
also you should probably consider writing this at the store level rather than the adapter level for the sake of re-use.
For some unknown reason, the record becomes part of the store default transaction. This code works for me:
var transaction = App.store.transaction();
var record = transaction.createRecord(App.Post);
record.set('someProperty', 'invalid value');
transaction.commit()
record.set('someProperty', 'a valid value');
App.store.commit(); // The record is created in backend
The problem is that after the first failure, you must always use the App.store.commit() with the problems it has.
Give a look at this gist. Its the pattern that i use in my projects.
https://gist.github.com/danielgatis/5550982
#josepjaume
Take a look at https://github.com/esbanarango/ember-model-validator.
Example:
import Model, { attr } from '#ember-data/model';
import { modelValidator } from 'ember-model-validator';
#modelValidator
export default class MyModel extends Model {
#attr('string') fullName;
#attr('string') fruit;
#attr('string') favoriteColor;
validations = {
fullName: {
presence: true
},
fruit: {
presence: true
},
favoriteColor: {
color: true
}
};
}