Validate presence of attributes using RSpec - rspec-rails

Some attributes in my model have presence validation and I wanted to add tests in my spec to check if an error is generated when the attribute is blank.
I'm using this code:
it 'should have a name' do
expect(#patient.errors[:name].size).to eq(1)
end
But here is the result of the rspec command:
Failures:
1) Patient should have a name
Failure/Error: expect(#patient.errors[:name].size).to eq(1)
expected: 1
got: 0
(compared using ==)
# ./spec/models/patient_spec.rb:11:in `block (2 levels) in '
Finished in 0.03002 seconds (files took 40.54 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./spec/models/patient_spec.rb:10 # Patient should have a name

With shoulda you can do this in one simple line:
Describe Patient do
# original 'should' validation
it { should validate_presence_of(:name) }
# alternative 'expected' validation
it { is_expected.to validate_presence_of(:name) }
end

I found my mistake. I need to call #patient.valid? before checking for errors.
it 'has a name' do
#patient.valid?
expect(#patient.errors[:name].size).to eq(1)
end

Related

RobotScript - Catch Python Code Exception

We have a following code in Python
def function1()
...........
raise Exception ..
...............
return 0
Robot script:
${STATUS}= function1
Can anyone please let me know how in Robot script we can catch the return code / exception and branch accordingly?
Run Keyword And Return Status will return a boolean true/false did the enclose keyword succeed.
Run Keyword And Ignore Error returns a tuple of two values - the 1st is the string "PASS" or "FAIL" depending did your keyword succeed or not; the second - the keyword's return value if it passed, or any error messages if not.
Thus surround your keyword with one of these 2 - it really boils down to do you care about the returned value in success or the error in failure - and work with the returned values.
${passed}= Run Keyword And Return Status function1
Run Keyword If ${passed} Action When Passed ELSE Different Action
${rc} ${msg} Run Keyword And Ignore Error function1
Run Keyword If "${rc}" == 'PASS' Log The keyword returned the value: ${msg}
... ELSE Log The keyword failed with the message: ${msg}

Robot Framework Variable Class File with triple Nested Dictionary is not dot notation accessible

Using the Robot Framework Documentation on Variable Files as a guide I implemented a Variable File Class with the get_variables. The basic example works as described.
When I implement a triple nested Dictionary (${A.B.C}) I can access the first two using ${A} and ${A.B} notation. However, when I want to access the third node ${A.B.C} the result is that I get an error
Resolving variable '${A.B.C}' failed: AttributeError: 'OrderedDict' object
has no attribute 'C'
In the below three examples I have an RF generated nested dictionary that I can access all nodes through the dot notation. The second example is a plain Python dictionary that is given back by the Variable Class. In the last example the Variable class returned is of the type OrderedDict.
Although the ${A['B']['C']['key']} works, it is more difficult to read in the code. When I load a similar yaml structure it supports the dot notation fully but this is not an option as the yaml file is static, and I require flexibility of Python for some of the key values.
So, I'm looking for some support on how to return a data structure that allows Robot Framework to interpret the full nested structure with the dot notation.
Variable Class File
from collections import OrderedDict
class OrderDict(object):
def get_variables(self):
C = OrderedDict([(u'key', u'value')])
B = OrderedDict([(u'C', C)])
A = OrderedDict([(u'B', B)])
D = {
u'E':
{
u'F':
{
u'key': u'value'
}
}
}
return OrderedDict([(u'DICT__A', A), (u'DICT__D', D)])
Robot Framework Script
*** Test Cases ***
Dictionary RF
${Z} Create Dictionary key=value
${Y} Create Dictionary Z=${Z}
${X} Create Dictionary Y=${Y}
Log To Console ${EMPTY}
Log To Console ${X}
Log To Console ${X['Y']['Z']['key']}
Log To Console ${X.Y}
Log To Console ${X.Y.Z}
Log To Console ${X.Y.Z.key}
Plain Dictionary Variable Class
Log To Console ${EMPTY}
Log To Console ${D}
Log To Console ${D['E']['F']['key']}
Log To Console ${D.E}
Log To Console ${D.E.F}
Log To Console ${D.E.F.key}
Ordered Dictionary Variable Class
Log To Console ${EMPTY}
Log To Console ${A}
Log To Console ${A['B']['C']['key']}
Log To Console ${A.B}
Log To Console ${A.B.C}
Log To Console ${A.B.C.key}
Robot Framework Console Log
Suite Executor: Robot Framework 3.0.2 (Python 2.7.9 on win32)
Dictionary RF
{u'Y': {u'Z': {u'key': u'value'}}}
value
{u'Z': {u'key': u'value'}}
{u'key': u'value'}
value
| PASS |
------------------------------------------------------------------------------
Plain Dictionary Variable Class
{u'E': {u'F': {u'key': u'value'}}}
value
{u'F': {u'key': u'value'}}
| FAIL |
Resolving variable '${D.E.F}' failed: AttributeError: 'dict' object has no attribute 'F'
------------------------------------------------------------------------------
Ordered Dictionary Variable Class
{u'B': OrderedDict([(u'C', OrderedDict([(u'key', u'value')]))])}
value
OrderedDict([(u'C', OrderedDict([(u'key', u'value')]))])
| FAIL |
Resolving variable '${A.B.C}' failed: AttributeError: 'OrderedDict' object has no
attribute 'C'
In the Robot Framework Slack channel Pekka Klarck pointed out that Robot Framework internally uses the robot.utils.DotDic class. Having get_variables() return a DotDic structure resolved my issue and I can now use the dot notation. Below is the code for the Variable Class DotDic (stored as DotDic.py).
from robot.utils import DotDict
class DotDic(object):
def get_variables(self):
G = {
u'H':
{
u'I':
{
u'key': u'value'
}
}
}
return {u'G': self.dict_to_dotdict(G)}
def dict_to_dotdict(self, dct):
dd = DotDict({})
for key, val in dct.items():
if isinstance(val, dict):
dd[key] = self.dict_to_dotdict(val)
else:
dd[key] = val
return dd

mruby-require error: NoMethodError: undefined method 'puts' for main

I managed to compile the mruby code adding the mrubygem - mruby-require from https://github.com/mattn/mruby-require
However when I try to call the require './' I get an error. Below is my code:
inc.rb
def test(a, b)
print "Inside the include->test(..)"
return a+b
end
test1.rb
require 'inc.rb'
def helloworld(var1)
print 'hello world ' + var1 + ". Test number = " + test(4, 5)
end
helloworld('test')
When I execute test1.rb I get this error from mruby:
NoMethodError: undefined method 'puts' for main
After some analysis I found out the 'puts' is not working with mruby. Infact after adding mruby-require gem, no ruby code gets execute. Do I need to add any dependency with mruby-require?
Can someone help me please?
Update: Pasting the content of build_config.rb as requested. I have removed the lines which are commented.
build_config.rb
MRuby::Build.new do |conf|
if ENV['VisualStudioVersion'] || ENV['VSINSTALLDIR']
toolchain :visualcpp
else
toolchain :gcc
end
enable_debug
# adding the mruby-require library
conf.gem 'mrbgems/mruby-require'
conf.gembox 'default'
end
MRuby::Build.new('host-debug') do |conf|
if ENV['VisualStudioVersion'] || ENV['VSINSTALLDIR']
toolchain :visualcpp
else
toolchain :gcc
end
enable_debug
conf.gembox 'default'
conf.cc.defines = %w(ENABLE_DEBUG)
conf.gem :core => "mruby-bin-debugger"
end
The following quote is from its README.md:
When mruby-require is being used, additional mrbgems that appear after mruby-require in build_config.rb must be required to be used.
This is from your build_config.rb:
conf.gem 'mrbgems/mruby-require'
conf.gembox 'default'
The default gembox contains mruby-print. So either require mruby-print or preferably swap the lines to make it a built-in gem (the default behavior without mruby-require).

Custom command result

When invoking a custom command, I noticed that only the logs are displayed. For example, if my Custom Comand script contains a retrun statement return "great custom command", I can't find it in the result. Both in API Java client or shell execution cases.
What can I do to be able to retrieve that result at the end of an execution?
Thanks.
Command definition in service description file:
customCommands ([
"getText" : "getText.groovy"
])
getText.groovy file content:
def text = "great custom command"
println "trying to get a text"
return text
Assuming that you service file contains the following :
customCommands ([
"printA" : {
println "111111"
return "222222"
},
"printB" : "fileB.groovy"
])
And fileB.groovy contains the following code :
println "AAAAAA"
return "BBBBBB"
Then if you run the following command : invoke yourService printA
You will get this :
Invocation results:
1: OK from instance #1..., Result: 222222
invocation completed successfully.
and if you run the following command : invoke yourService printB
You will get this :
Invocation results:
1: OK from instance #1..., Result: AAAAAA
invocation completed successfully.
So if your custom command's implementation is a Groovy closure, then its result is its return value.
And if your custom command's implementation is an external Groovy file, then its result is its last statement output.
HTH,
Tamir.

Issue using If statments in Unix

I'm new to shell scripting and need some help. I am trying to write a script to bounce some servers and I am having a few issues with my if statements. The First and Second one below is giving me a too many arguments error.
For the first one, I am the variable $jmsProcess is a ps -ef | grep command and I only want to go into the if-statement, if this returns some results. This is the same issue for the second one.
In the Third if-statement I want it to check if either of those variables have the value true but this gives me a
if[ [ false || false ] == true ]: command not found
Error.
#Check the JMS process has been killed
if [ $jmsProcess != null ] # SHOULD THIS BE NULL???
then
echo "JMS Process is still running"
$jmsRunning = "true"
fi
#Check the Bone process has been killed
if [ $boneProcess != null ] # SHOULD THIS BE NULL???
then
echo "B-One Process is still Running"
$boneRunning = "true"
fi
if[ [ $jmsRunning || $boneRunning ] == true ] # CHECK THIS FOR QUOTES
then
# $killProcess
fi
null is not a Bash keyword. If you want to check whether a variable is defined, you can do the following:
if [ "${var+defined}" = defined ]
To check whether it's empty or undefined:
if [ -z "${var-}" ]
We don't know how you're setting any of the variable values, (jmsProcess, boneProcess).
Try surrounding all var values like "$var" (with dbl-quotes) and see if the error messages change.
Also there are numerous syntax issues in code visible above. Hard to tell if it is an artifact of posting here, (The code block feature is pretty robust), so I'm going to comment on what I see wrong.
if[ [ false || false ] == true ]: command not found
There are a lot of issues here: false is an shell command. Try typing it on the command line and then do echo $?. you should see 1. true; echo $? will return 0. But the if statements continue or fall-over to the else block based on the last return code (with some special case exceptions).
Also, I'm guessing you're trying to make some sort of reg exp with [ false || false ] == true. Won't work. see below.
You can set status variables to have the value of false (or true) which will be evaluated correctly by the shell.
Also, if[ will give the 'command not found' msg. So by using vars that have the value false, you can do
Try
jmsRunning=false ; boneRunning=true
if [[ ${jmsRunning} || ${boneRunning} ]] ; then
echo both NOT running
else
echo at least 1 is running
fi
Change both to false to see the message change.
Also, null is just a string in a shell script, you probably mean "".
Finally, var assignments cannot have spaces surrounding the '=' sign AND do not use the '$' char at the front when it is on the left hand side of the statment, i.e.
boneRunning=true
I hope this helps.

Resources