What's wrong with this Factory Girl definition - factory-bot

#test/factories.rb
Factory.define :estado do |estado|
estado.nombre "Distrito Federal"
end
Factory.define :municipio do |municipio|
municipio.nombre "Cuauhtémoc"
municipio.estado { |estado| estado.association(:estado) }
end
Factory.define :colonia do |colonia|
colonia.nombre "Condesa"
colonia.municipio { |municipio| municipio.association(:municipio) }
end
#test/units/user_test.rb
test "Whats wrong with this"
assert(Factory.create(:colonia).id != 0)
end
The test fails miserably because Factory.create(:colonia) ALWAYS create a Colonia object with and id equals 0!!! #_#
Why is this factory creating objects with id 0?

It looks like a problem with the structure of your DB to me.
Is the id column in your 'colonias' table set to autoincrement?

Related

How to check if an argument of an object is in an ArrayBuffer filled with objects in Scala?

I want to check if an Int typed by an user exists as primary argument/variable(the class has only one argument of type Int) in an ArrayBuffer filled with objects of a class.
It's an assignment for school, and I'm not able to get help of a prof or assistant so I'm asking for your help. I have to code a class "ewallet", which has attributes like "client id"(Int) and "pin code" (random Int between two Numbers). I'm not using "pin code" as an argument of the class as it seems to be implied in the assignment as it says "It has to show the pass when the user creates an account using his client id". I shouldn't be able to create 2 ewallets with the same client id.
So I would have to refuse to create an ewallet when if an ewallet with the same client id exists already in the ArrayBuffer (or array) that stocks ewallets.
Because of the Randomly generated "pin code", it creates different ewallets with same client id and different pin codes. So how to not add an ewallet(class) to a list if an ewallet with some argument exists already?
Thanks for helping a newbie.
I could just created another array list saving the client id's entered by an user and save them to compare with future client id's. But I'd like to learn how to do with an array containing objects.
I tried with for (i <- ListClients) if (NumClient != i.id) but if the list is empty, it doesn't do anything...
class ewallet(clientID: Int){
val id = clientID
val pass = 100 + Random.nextInt((99999-100)+1) //for the class, I didnt include the rest as its not related.
//for the main
def main(args: Array[String]): Unit = {
var ListClients = ArrayBuffer[ewallet]()
var action: Char = " ".charAt(0)
do {
println("[c]-Create ewallet. \n[a]-Access ewallet.\n[q]-Quit")
action = StdIn.readChar()
if (action == 'c') {
val NumClient = StdIn.readLine("Enter your client id :").toInt
var newClient = new ewallet(NumClient)
for (i <- ListClients) if (NumClient == i.id) {
println("Impossible, already exists.")
}
for (i <- ListClients) if (NumClient != i.id){
ListClients += newClient
println("Your pin code is : " + newClient.pass)
}
}
println(ListClients.mkString("\n"))
} while(action != 'q')
I should be able to add newClient to ListClients if NumClient != i.id, but because it's initially empty, it doesn't read those lines… So it does Nothing.
The simplest way would be to assign the result of the presence check to a variable, and add or "not add" the client object based on this variable. In Scala, the idiomatic way to work with collections are their rich set of transformation methods; in your case, exists provides the solution:
val alreadyExists = ListClients.exists(_.id == NumClient)
if (alreadyExists) {
println("Impossible, already exists.")
} else {
ListClients += newClient
println("Your pin code is : " + newClient.pass)
}
If you don't know yet about collection transformations and higher-order functions in general (and you should! they make life a lot easier), then the above piece is actually equivalent to this:
var alreadyExists = false
for (i <- ListClients) {
alreadyExists = alreadyExists || i.id == NumClient
}
(albeit a bit more efficient since it stops the iteration right after the existing client is found, if it is at all present).
As an unrelated comment, in Scala it is conventional to name variables in pascalCase and types in CamelCase. Thus, your class should be called something like EWallet, and variables like ListClients should be called listClients. Also, " ".charAt(0) is the same as ' '.

How to pass a null value received on msg.req.query to msg.payload

I am developing an application using Dashdb on Bluemix and nodered, my PHP application uses the call to webservice to invoke the node-red, whenever my function on PHP invokes the node to insert on table and the field GEO_ID is null, the application fails, I understand the issue, it seems the third parameter was not informed, I have just tried to check the param before and passing something like NULL but it continues not working.
See the code:
msg.account_id = msg.req.query.account_id;
msg.user_id = msg.req.query.user_id;
msg.geo_id=msg.req.query.geo_id;
msg.payload = "INSERT INTO ACCOUNT_USER (ACCOUNT_ID, USER_ID, GEO_ID) VALUES (?,?,?) ";
return msg;
And on Dashdb component I have set the parameter as below:
msg.account_id,msg.user_id,msg.geo_id
The third geo_id is the issue, I have tried something like the code below:
if(msg.req.query.geo_id===null){msg.geo_id=null}
or
if(msg.req.query.geo_id===null){msg.geo_id="null"}
The error I got is the one below:
dashDB query node: Error: [IBM][CLI Driver][DB2/LINUXX8664] SQL0420N Invalid character found in a character string argument of the function "DECIMAL". SQLSTATE=22018
I really appreciate if someone could help me on it .
Thanks,
Eduardo Diogo Garcia
Is it possible that msg.req.query.geo_id is set to an empty string?
In that case neither if statement above would get executed, and you would be trying to insert an empty string into a DECIMAL column. Maybe try something like this:
if (! msg.req.query.geo_id || msg.req.query.geo_id == '') {
msg.geo_id = null;
}

Need an IF-ELSE inside a CASE-WHEN choice

I've got an existing stored procedure that looks like this:
SELECT TOP 1
...
CASE PX.Client.value('(Type)[1]', 'varchar(25)')
WHEN 'Sole Proprietor' THEN 'SPR'
WHEN 'Partnership' THEN 'PAR'
WHEN 'Corp (C)' THEN 'COR'
WHEN 'Corp (S)' THEN 'SCO'
WHEN 'LimitedCorp' THEN 'LLC'
WHEN 'Trust' THEN 'TRU'
END AS MyStructure,
...
INTO #Prod
FROM
#XMLIN.nodes('/MyDataset/MyRegistration') AS PX(Client)
Everything works great except I need to change the logic. Right now if Type is "LimitedCorp" then MyStructure is always "LLC". But I need to change it so that it sub-divides MyStructure based on the TaxClassification like so (pseudo-code):
...
WHEN 'LimitedCorp' THEN
IF PX.Client.value('(TaxClassification)[1]') == 'Partnership' THEN 'LP'
ELSE IF PX.Client.value('(TaxClassification)[1]') == 'SCorp' THEN 'LLS'
ELSE 'LLC'
WHEN 'Trust' ...
In my .NET code this would be a piece of cake! I'm not very strong on my stored procedure syntax though! Thanks!
Nest another case:
WHEN 'LimitedCorp' THEN
case
when PX.Client.value('(TaxClassification)[1]') == 'Partnership' then 'LP'
when PX.Client.value('(TaxClassification)[1]') == 'SCorp' then 'LLS'
else 'LLC'
end
WHEN 'Trust' THEN 'TRU'

What is the purpose of this test case here?

Could someone explain what this code is doing to me? I don't understand the purpose of the system.debug lines.
Test.startTest();
// 1. First check to see if it's a brand new Owner ID
System.debug('first test'); // Creating a new opportunity to start Trigger
Opportunity newtestOpp1 = TestUtil.initOpportunity(TestUtil.initAccount(),TestUtil.initContact());
User testUser1 = TestUtil.initUser();
newtestOpp1.OwnerId = testUser1.Id;//setting OwnerId
System.debug('The opp owner should be null' + newtestOpp1.Op_Owner__c);
try{
insert newtestOpp1;
} catch ( DMLException d ) {
System.debug(d);
}
System.debug('The opp owner should not be null' + newtestOpp1.Op_Owner__c);
Looks to me like it's supposed to be testing whether some kind of workflow or trigger is setting a value in the Op_Owner__c field upon inserting an Opportunity record. The debug statements should actually be System.assert or System.assertEquals calls though, if the test is meant to actually verify the application's functionality. Debug statements aren't typically viewed during test case execution.
Here's a cleaned-up version that actually makes assertions about the Op_Owner__c field's value (which is the purpose of a test case), rather than just printing something to the debug log.
Test.startTest();
Opportunity newtestOpp1 = TestUtil.initOpportunity(TestUtil.initAccount(),TestUtil.initContact());
User testUser1 = TestUtil.initUser();
newtestOpp1.OwnerId = testUser1.Id;//setting OwnerId
System.assertEquals(null, newtestOpp1.Op_Owner__c, 'The opp owner should be null');
try{
insert newtestOpp1;
} catch ( DMLException d ) {
System.debug(d);
}
System.assertNotEquals(null, newtestOpp1.Op_Owner__c, 'The opp owner should not be null');

It is possible to execute MySQLi prepared statement before the other one is closed?

Lets say I have a prepared statement. The query that it prepares doesn't matter. I fetch the result like above (I can't show actual code, as it is something I don't want to show off. Please concentrate on the problem, not the examples meaningless) and I get
Fatal error: Call to a member function bind_param() on a non-object in... error. The error caused in the called object.
<?php
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
class table2Info{
private $mysqli;
public function __construct($_mysqli){
$this->mysqli = $_mysqli;
}
public function getInfo($id)
{
$db = $this->mysqli->prepare('SELECT info FROM table2 WHERE id = ? LIMIT 1');
$db->bind_param('i',$db_id);
$db_id = $id;
$db->bind_result($info);
$db->execute();
$db->fetch();
$db->close();
return $info;
}
}
$t2I = new table2Info($mysqli);
$stmt->prepare('SELECT id FROM table1 WHERE name = ?');
$stmt->bind_param('s',$name);
$name = $_GET['name'];
$stmt->bind_result($id);
$stmt->execute();
while($stmt->fetch())
{
//This will cause the fatal-error
echo $t2I->getInfo($id);
}
$stmt->close();
?>
The question is: is there a way to do another prepared statement while another one is still open? It would simplify the code for me. I can't solve this with SQL JOIN or something like that, it must be this way. Now I collect the fetched data in an array and loop through it after $stmt->close(); but that just isn't good solution. Why should I do two loops when one is better?
From the error you're getting it appears that your statement preparation failed. mysqli::prepare returns a MySQLi_STMT object or false on failure.
Check for the return value from your statement preparation that is causing the error. If it is false you can see more details by looking at mysqli::error.