How to terminate ruby unit test with "Pass" or success status - ruby

First of all thank you very much for reading this question.
I am using Ruby-1.8.7 and Webdriver to connect to FF browser. I am testing our product functionality. There is a form and I am giving wrong input and expecting error message. This is 5 steps (pages) process and when I click on next button I may get error based on my input on that particular page. Error comes only when there is wrong input and I click on next button. If I get expected error message, I should mark test as pass. Simple example is if I enter too long description in the Description field, system will throw error message "Description too long."
Problem here is While my testing whenever I get this kind of expected error, I want to terminate Ruby unit test with Pass/Success and execute new test.
I tried different way but can not set the test as pass/success.
Sample code.
def enterdata()
...
click_next_and_check_for_error_message(timeout,expected_message)
set_file_server_settings(args)
click_next_and_check_for_error_message(timeout,expected_message)
set_select_filters(args)
click_next_and_check_for_error_message(timeout,expected_message)
set_registration_scope(args)
click_next_and_check_for_error_message(timeout,expected_message)
set_schedule_scan(args)
click_next_and_check_for_error_message(timeout,expected_message)
end
def click_next_and_check_for_error_message(...)
...
if !message.empty?
print "\nExpected is #{exp_msg}"
print "\nActual is #{message}"
if (exp_msg == message)
#if assert_equal( exp_msg, message, "Expected message #{exp_msg} did not come" )
print "\n*** MATACHED ***\n"
raise TestPassed
else
raise ApplianceFailure, message
end
end
With both exo_msg and message are same, test should be terminated with success as I was expecting it.
Please guide me.
Test::Unit

Related

Missing a value during form checking test using rspec and capybara

I'm dealing with a bug from a spec file, specifically in a test which is related to an action of update a field value, this is the code I'm trying to use:
it "is possible to update your city destination page" do
click_link another_city.name
expect(page).to have_content(country.name)
expect(page).to have_content(country.state)
expect(page).to have_content(city.name)
end
After run the test I get the message:
Failure/Error: expect(page).to have_content(city.name) expected to find text "Melbourne" in "..."
So, I'm trying to fix it with this new line of code:
expect(page).to have_field(another_dealer.name, with: 'Voonte')
But I got a different kind of error related to another field.
So, my questions are:
is it a good approach trying to add a specific value in the spec?
what else should I try to fix the error?
Thanks a lot for your comments.

Mongoid Validation Error "Email Can't be blank" when testing with rspec & Capybara, but fields are not blank

I am running into an error when writing an rSpec Capybara test to mock a user signing up for the website.
It should be noted that, unfortunately, I am writing a test for a codebase that is entirely new to me, so a lot of the code for the main program is unknown to me. If asked for something I will try and dig up the relevant code, but I'm not certain what else to include at the moment. However I can say it has been successfully running in production for a while, and I can manually test it successfully - so I think the error is probably in my test, or perhaps some configuration used just while testing.
rspec test
RSpec.describe 'New User Sign Up', type: :feature do
scenario 'valid signup inputs' do
visit("/users/sign_up")
fill_in 'user_name', with: 'TEST'
fill_in 'user_email', with: 'TEST#test.com'
fill_in 'user_username_with_caps', with: "TEST"
fill_in 'user_password', with: 'TESTpw123'
puts find_field('user_email').value
puts expect(find_field('user_email').value).to eq 'TEST#test.com'
puts expect(page).to have_selector("input[value='TEST#test.com']")
puts page.should have_field('user_email', with: 'TEST#test.com')
click_on 'Create an account'
end
end
The output is:
bgc#jadzia:~/Documents/Work/BadgeList/code/badgelist/backend/spec$ bundle exec rspec sign_up_spec.rb
TEST#test.com
true
true
true
F
Failures:
1) New User Sign Up valid signup inputs
Failure/Error: click_on 'Create an account'
Mongoid::Errors::Validations:
message:
Validation of User failed.
summary:
The following errors were found: Email can't be blank
resolution:
Try persisting the document with valid data or remove the validations.
Note the puts statements and the corresponding output before the error message.
As far as I can tell, the fields ARE getting filled in properly. However, somehow this does not get recognized when it attempts to complete the sign up. The error is coming from Mongoid, so somehow mongo reacts differently to an testing auto-entered field vs. a manually entered one.
It should also be noted that, if I disable database_cleaner-mongoid, and run the same test twice... I get a -DIFFERENT- outcome. The test technically passes, but there is a warning prompt on the page that says "This email is taken".
So, somehow the value in the email field is...
Being entered/read properly when directly querying the field value on the page
Not recognized when it immediately afterwards tries to use that value to Create an account, instead the field is seen as blank.
But ALSO the field is successfully saved into the DB for a new account with this information, so running the same test again creates a conflict with the entry from the previous test if the DB is not cleaned first.
All click_on does is click on the button. It doesn't wait for the server to do anything, or anything on the page to change, etc. So ending the test with click_on isn't actually testing for any behavior, and the DB is going to get reset while the action triggered by click_on is still occurring, which is unlikely to be what you want. You need to add an expectation after the click_on testing for what you expect to see in the page like
...
click_on 'Create an account'
expect(page).to have_text('User created!!!)
Also note that the expectations you are calling puts on aren't actually defined to return anything specific, so the fact you're seeing true really is just luck. They're defined to not raise an error when successful, and raise an error when not.

RSpec Testing for Slack-Ruby-Bot Commands

I have been implementing a basic slack bot to a channel and as the code is very simple I have no public methods. Just commands from slack-ruby-bot gem. But as project requirement I need to add several unit testing to my project. Basically when I give command of #ruby_codes strings it gives me the wiki page of that area. how can I test this? attached my version but tests fail everytime.
My command example is as follows:
module RubyCodes
# SlackBot command methods#
class GetWiki < SlackRubyBot::Commands::Base
command 'strings' do |client, data, _match|
client.say(channel: data.channel, text: 'https://en.wikipedia.org/wiki/Ruby_(programming_language)#Strings')
end
My test case is as follows:
describe SlackRubyBot::Commands do
it 'returns ruby strings wiki page' do
expect(message: "#{SlackRubyBot.config.user} strings").to respond_with_slack_message('https://en.wikipedia.org/wiki/Ruby_(programming_language)#Strings')
end
end
Thanks in advance!
also, this is the error I get:
expected to receive message with text: https://en.wikipedia.org/wiki/Ruby_(programming_language)#Strings once,
received:[{:text=>"Sorry <#user>, I don't understand that command!", :channel=>"channel"}]

Rspec test - keep executing a method until the error message is no longer raised

I'm new to Rspec, so sorry if this is a bad question. In one of the test tests I'm running, I have code which uses a random number generator to determine whether or not a method should be executed. If it cannot be executed, the method raises an error message.
So I need to write a test which continually runs the method on a small array of class objects until it no longer receives the error message. So in effect each class object will eventually successfully execute that method after a few tries.
The array has 6 items. I'm hoping that I need to loop through each one and then use a while loop which then tests whether the error message has been executed, but I haven't got a clue how. Any help gratefully appreciated.
I have something like this at the moment...
def create_planes
6.times do
plane=Plane.new
planes<<plane
end
end
it 'should land each plane' do
create_planes
i = 0
while i<planes.count
begin
airport.plane_land(planes[i])
i++
rescue
next
end
end
expect(airport.plane_count).to eq(6)
end
Generally with RSpec, you'll set up your inputs and test your outputs. You wouldn't execute until an error occurs, you'd execute a known number of lands and then check that the airport's plane changed to what you expect.
it "should maintain a list of landed planes" do
expect {
3.times { airport.plane_land Plane.new }
}.to change { airport.plane_count }.from(0).to(3)
end

Ruby append to string if error contains string

I have a Slack Bot that needs to respond in an error condition. If the error has certain text in it, I want to append some additional information to the return message. This block of code works fine if I comment out the message += line but breaks if I do not. When I try to replicate this in irb everything works fine too.
Does something look obviously wrong here?
begin
scan = #nsc.scan_devices(devices)
rescue Nexpose::APIError => e
puts "[!] API ERROR: Most likely caused by an orphaned asset (#{device_ids})"
puts "[!] #{e}"
$slackbot_logger.error("[!] API ERROR: Most likely caused by an orphaned asset (#{device_ids})")
$slackbot_logger.error(e)
# Message back to Slack
message = "<##{user_id}> scan for #{ip_list} *failed* :sob:"
message += 'There is a scheduled blackout Tues/Thurs until 1000 CST' if e.include? 'blackout'
SlackFunctions.slack_send_message(message, channel)
return
end
This particular error object (and maybe all error objects) did not have an include? method. Therefore using e.to_s seems to do the trick.

Resources