Why can't I get a be_nil test to fail in Rspec - ruby

In Rspec I have the following:
describe "triangle.parameter" do
it "should return nil when it has 0 sides" do
#triangle = Triangle.new({})
#triangle.paramater.should be_nil
end
end
And I have my parameter method like so:
def parameter
return 4
end
I've tried true, false, 4, "apple" for parameter to return and nothing will fail. I also can't get it to fail with nothing in the method. What am I doing wrong?

You have #triangle.paramater instead of #triangle.parameter; since it doesn't know what paramater is, it will always be nil.

Related

Simplifying `if then` blocks

I have several instances of code that look like this:
if checkProperties(top_properties, payload) == false
return false
end
checkProperties has only one return for false depending on some condition:
def checkProperties(properties, to_check)
properties.each do |property|
if to_check[property.to_s].nil? or to_check[property.to_s].blank?
log_err("Something went wrong")
return false
end
end
end
However I feel this can be simplified. Is it valid to just use the following?
return false unless checkProperties(top_properties, payload)
Any other suggestions?
Don’t return from blocks in the first place. Use break instead:
def checkProperties(properties, to_check)
properties.each_with_object(true) do |property, _|
if to_check[property.to_s].to_s.empty?
log_err("Something went wrong")
break false
end
end
end
or use any? and/or all?:
def checkProperties(properties, to_check)
(!properties.any? { |p| to_check[p.to_s].to_s.empty? }).tap do |good|
log_err("Something went wrong") unless good
end
end
To explicitly show what property was missing, use Enumerable#find:
def empty_property?(properties, to_check)
!!(properties.find { |p| to_check[p.to_s].to_s.empty? }.tap do |prop|
log_err("Property #{prop.inspect} was missing") unless prop.nil?
end)
end
I also took a liberty to renamed a method to follow Ruby naming convention (snake case with a question mark on the end for methods returning true/false.)
Double bang trick is needed to produce true/false out of possible values returned from find: the missing property or nil.
You can check with all? enumerator. This will return true only if all has values below:
def checkProperties(properties, to_check)
properties.all? { |p| to_check[p.to_s] && !to_check[p.to_s].blank? }
end
If any of the property in to_check is nil/absent, all? will return false and stop iterating from there.
Any other suggestions?
A custom error class would work:
class PropertyError < StandardError
end
You could raise it when encountering a missing property:
def check_properties(properties, to_check)
properties.each do |property|
raise PropertyError if to_check[property.to_s].blank?
end
end
This would eliminate the need for conditionals and explicit returns, you'd just have to call:
def foo
check_properties(top_properties, payload)
# do something with top_properties / payload
end
And somewhere "above" you could handle the logging:
begin
foo
rescue PropertyError
log_err 'Something went wrong'
end
Of course, you can also store the missing property's name or other information in the exception to provide a more meaningful error / log message.

.visible? doesn't give false when element not visible

There are test cases where I want to check:
Load more button visible
Load more not visible
I wrote this method:
def loadmore_button_visible?
wait_until(20) do
#browser.refresh
link_element(:title => 'load_more').visible?
end
end
and used it as
expect(on(ProductViewPage).loadmore_button_visible?).to be_true for "test1"
and expect(on(ProductViewPage).loadmore_button_visible?).to be_false for "test2"
It works test1 but for test2 it gives Time Out Error. I think I have asked similar question here wait_until block is giving time out error
but this time I think its not about wait_until block as wait_until works for "test1".
Your wait_until block is expecting to resolve to true. If it does not, it will raise a TimeoutError. The first test passes because link_element(:title => 'load_more').visible? is true and that satisfies the wait_until method. If you want the method to return true and false, you need to catch the error and explicitly return false. Something like:
def loadmore_button_visible?
begin
wait_until(20) do
#browser.refresh
link_element(:title => 'load_more').visible?
end
rescue TimeoutError
false
end
end

Rspec 3.0 How to mock a method replacing the parameter but with no return value?

I've searched a lot and just cannot figure this out although it seems basic. Here's a way simplified example of what I want to do.
Create a simple method that does something but doesn't return anything, such as:
class Test
def test_method(param)
puts param
end
test_method("hello")
end
But in my rspec test I need to pass a different parameter, such as "goodbye" instead of "hello." I know this has to do with stubs and mocks, and I've looking over the documentation but can't figure it out: https://relishapp.com/rspec/rspec-mocks/v/3-0/docs/method-stubs
If I do:
#test = Test.new
allow(#test).to_receive(:test_method).with("goodbye")
it tells me to stub out a default value but I can't figure out how to do it correctly.
Error message:
received :test_method with unexpected arguments
expected: ("hello")
got: ("goodbye")
Please stub a default value first if message might be received with other args as well.
I am using rspec 3.0, and calling something like
#test.stub(:test_method)
is not allowed.
How to set a default value that is explained at
and_call_original can configure a default response that can be overriden for specific args
require 'calculator'
RSpec.describe "and_call_original" do
it "can be overriden for specific arguments using #with" do
allow(Calculator).to receive(:add).and_call_original
allow(Calculator).to receive(:add).with(2, 3).and_return(-5)
expect(Calculator.add(2, 2)).to eq(4)
expect(Calculator.add(2, 3)).to eq(-5)
end
end
Source where I came to know about that can be found at https://makandracards.com/makandra/30543-rspec-only-stub-a-method-when-a-particular-argument-is-passed
For your example, since you don't need to test the actual result of test_method, only that puts gets called in it passing in param, I would just test by setting up the expectation and running the method:
class Test
def test_method(param)
puts param
end
end
describe Test do
let(:test) { Test.new }
it 'says hello via expectation' do
expect(test).to receive(:puts).with('hello')
test.test_method('hello')
end
it 'says goodbye via expectation' do
expect(test).to receive(:puts).with('goodbye')
test.test_method('goodbye')
end
end
What it seems you're attempting to do is set up a test spy on the method, but then I think you're setting up the method stub one level too high (on test_method itself instead of the call to puts inside test_method). If you put the stub on the call to puts, your tests should pass:
describe Test do
let(:test) { Test.new }
it 'says hello using a test spy' do
allow(test).to receive(:puts).with('hello')
test.test_method('hello')
expect(test).to have_received(:puts).with('hello')
end
it 'says goodbye using a test spy' do
allow(test).to receive(:puts).with('goodbye')
test.test_method('goodbye')
expect(test).to have_received(:puts).with('goodbye')
end
end

Does should_receive do something I don't expect?

Consider the following two trivial models:
class Iq
def score
#Some Irrelevant Code
end
end
class Person
def iq_score
Iq.new(self).score #error here
end
end
And the following Rspec test:
describe "#iq_score" do
let(:person) { Person.new }
it "creates an instance of Iq with the person" do
Iq.should_receive(:new).with(person)
Iq.any_instance.stub(:score).and_return(100.0)
person.iq_score
end
end
When I run this test (or, rather, an analogous one), it appears the stub has not worked:
Failure/Error: person.iq_score
NoMethodError:
undefined method `iq_score' for nil:NilClass
The failure, as you might guess, is on the line marked "error here" above. When the should_receive line is commented out, this error disappears. What's going on?
Since RSpec has extended stubber functionality, now following way is correct:
Iq.should_receive(:new).with(person).and_call_original
It will (1) check expectation (2) return control to original function, not just return nil.
You're stubbing away the initializer:
Iq.should_receive(:new).with(person)
returns nil, so Iq.new is nil. To fix, just do this:
Iq.should_receive(:new).with(person).and_return(mock('iq', :iq_score => 34))
person.iq_score.should == 34 // assert it is really the mock you get

How to use yield self within Rspec

This is a description of how to create a helper method in Rspec taken from the Rspec book (page 149). This example assumes that there is a method called 'set_status' which is triggered when the 'Thing' object is created.
Both sets of code create a new 'Thing' object, set the status, then do 'fancy_stuff'. The first set of code is perfect clear to me. One of the 'it' statements it triggered, which then calls the 'create_thing' method with options. A new 'Thing' object is created and the 'set_status' method is called with the 'options' attribute as the parameter.
The second set of code is similar. One of the 'it' statements is triggered, which then calls the 'given_thing_with' method while passing ':status' hash assignment as a parameter. Within the 'given_thing_with' method the 'yield' is triggered taking the 'Thing.new' as a parameter. This is where I am having trouble. When I try to run this code I get an error of "block given to yield". I understand that whatever attributes that are passed by yield will be returned to the 'thing' in pipe brace from the 'it' statement that called the 'given_thing_with' method. I can get the new
What I don't understand is why the code block is not called in the 'given_thing_with' method after the 'yield' command. In other words, I can't code in that block to run.
Thanks in advance for your help.
The remainder of this question is quoted directly from the Rspec book:
describe Thing do
def create_thing(options)
thing = Thing.new
thing.set_status(options[:status])
thing
end
it "should do something when ok" do
thing = create_thing(:status => 'ok')
thing.do_fancy_stuff(1, true, :move => 'left', :obstacles => nil)
...
end
it "should do something else when not so good" do
thing = create_thing(:status => 'not so good')
thing.do_fancy_stuff(1, true, :move => 'left', :obstacles => nil)
...
end
end
One idiom you can apply to clean this up even more is to yield self from initializers in your objects. Assuming that Thing's initialize() method does this and set_status() does as well, you can write the previous like this:
describe Thing do
def given_thing_with(options)
yield Thing.new do |thing|
thing.set_status(options[:status])
end
end
it "should do something when ok" do
given_thing_with(:status => 'ok') do |thing|
thing.do_fancy_stuff(1, true, :move => 'left', :obstacles => nil)
...
end
end
it "should do something else when not so good" do
given_thing_with(:status => 'not so good') do |thing|
thing.do_fancy_stuff(1, true, :move => 'left', :obstacles => nil)
...
end
end
end
The example in the book is a bit confusing because the implementation of Thing is not shown. To make this work you need to write Thing like so:
class Thing
def initialize
yield self
end
end
When given_thing_with is called it yields a new Thing, which will yield itself when it is constructed. This means that when the inner code block (the one containing thing.set_status) is executed it will have a reference to he newly built Thing.
There are 2 issues with the code from book.
1. Setting up the initializer to yield itself
When the Thing object is created, it needs an initializer and need yield itself.
class Thing
def initialize
yield self
end
end
However, this alone will still causes an error, at least on my system, which is Ruby 1.9.3. Specifically, the error is 'block given to yield (SyntaxError)'. This doesn't make much sense, since that is what we want it to do. Regarless, that is the error I get.
2. Fixing the 'block given to yield' error
This is not as obvious and has something to do with either Ruby or the 'yield' statement, but creating a block using 'do...end' as was written in the book and is shown below causes the error.
yield Thing.new do |thing|
thing.set_status(options[:status])
end
Fixing this error is simlpy a matter of creating the block using braces, '{...}', as is shown below.
yield Thing.new { |thing|
thing.set_status(options[:status])
}
This is not good form for multiline Ruby code, but it works.
Extra. How the series of yields works to set the parameters of the 'Thing' object
The problem is already fixed, but this explains how it works.
the "caller block" calls 'given_thing_with' method with a parameter
that method yields back to the "caller block" a new "Thing" and a block (I'll call it the "yield block")
to execute the "yield block", the Thing class needs the initialization and 'yield self', otherwise the 'set_status' method will never be run because the block will be ignored
the new "Thing" is already in the "caller block" and has it's status set and now the relevant method is executed

Resources