def some_helper(exam)
x = 1
y = 2
if condition1
x = 3
y = 4
end
if condition2
x = 5
y = 6
end
return_something_base_on_x_y(x,y)
end
def return_something_base_on_x_y(x,y)
return "#{1}/#{2}" if x==1, y==2
return "#{3}/#{4}" if x==3, y==4
return "#{5}/#{6}" if x==5, y==6
end
i will call in view like this
some_helper(exam) # exam is an object
How can i write rspec for some_helper ? Can i write something like bellow. Only test the argument pass to method
describe "#some_helper" do
let(:exam) { Exam.create exam_params }
context "condition 1" do
it do
expect "some_helper" already call return_something_base_on_x_y with arguments(1,2) inside them
expect "some_helper" already call return_something_base_on_x_y with arguments(3,4) inside them
expect "some_helper" already call return_something_base_on_x_y with arguments(5,6) inside them
end
end
end
Can i avoid to write like
expect(some_helper(exam)).to eq "123" # and 456.
Because if condition is more complexity, i have to get a list of return_something_base_on_x_y result.
You can set expectations on a method before it is called by using a double:
it "sets an expectation that a method should be called"
obj = double('obj')
expect(obj).to recive(:foo).with('bar')
obj.foo('bar')
end
The example is failed if obj.bar is not called.
You can set expectations on an object after the call is done by using spies:
obj = spy('obj')
obj.foo('bar')
expect(obj).to have_recived(:foo).with('bar')
This allows you to arrange your tests after the act, arrange, assert pattern (or given, then, when in BDD terms).
Can i avoid to write like
expect(some_helper(exam)).to eq "123" # and 456.
Yes, but it might actually degrade your tests. Stubbing can mask bugs and makes your code more about testing the implementation (how the code does its job) then the behavior (the result).
Stubbing is most suitible when the object you're testing touches an application boundry or is not idempotent (like for example a method that generates random values).
Related
I was trying to DRY up a Rails controller by extracting a method that includes a guard clause to return prematurely from the controller method in the event of an error. I thought this may be possible using a to_proc, like this pure Ruby snippet:
def foo(string)
processed = method(:breaker).to_proc.call(string)
puts "This step should not be executed in the event of an error"
processed
end
def breaker(string)
begin
string.upcase!
rescue
puts "Well you messed that up, didn't you?"
return
end
string
end
My thinking was that having called to_proc on the breaker method, calling the early return statement in the rescue clause should escape the execution of foo. However, it didn't work:
2.4.0 :033 > foo('bar')
This step should not be executed in the event of an error
=> "BAR"
2.4.0 :034 > foo(2)
Well you messed that up, didn't you?
This step should not be executed in the event of an error
=> nil
Can anyone please
Explain why this doesn't work
Suggest a way of achieving this effect?
Thanks in advance.
EDIT: as people are wondering why the hell I would want to do this, the context is that I'm trying to DRY up the create and update methods in a Rails controller. (I'm trying to be agressive about it as both methods are about 60 LoC. Yuck.) Both methods feature a block like this:
some_var = nil
if (some complicated condition)
# do some stuff
some_var = computed_value
elsif (some marginally less complicated condition)
#error_msg = 'This message is the same in both actions.'
render partial: "show_user_the_error" and return
# rest of controller actions ...
Hence, I wanted to extract this as a block, including the premature return from the controller action. I thought this might be achievable using a Proc, and when that didn't work I wanted to understand why (which I now do thanks to Marek Lipa).
What about
def foo(string)
processed = breaker(string)
puts "This step should not be executed in the event of an error"
processed
rescue ArgumentError
end
def breaker(string)
begin
string.upcase!
rescue
puts "Well you messed that up, didn't you?"
raise ArgumentError.new("could not call upcase! on #{string.inspect}")
end
string
end
After all this is arguably a pretty good use case for an exception.
It seems part of the confusion is that a Proc or lambda for that matter are distinctly different than a closure (block).
Even if you could convert Method#to_proc to a standard Proc e.g. Proc.new this would simply result in a LocalJumpError because the return would be invalid in this context.
You can use next to break out of a standard Proc but the result would be identical to the lambda that you have now.
The reason Method#to_proc returns a lambda is because a lambda is far more representative of a method call than a standard Proc
For Example:
def foo(string)
string
end
bar = ->(string) { string } #lambda
baz = Proc.new {|string| string }
foo
#=> ArgumentError: wrong number of arguments (given 0, expected 1)
bar.()
#=> ArgumentError: wrong number of arguments (given 0, expected 1)
baz.()
#=> nil
Since you are converting a method to a proc object I am not sure why you would also want the behavior to change as this could cause ambiguity and confusion. Please note that for this reason you can not go in the other direction either e.g. lambda(&baz) does not result in a lambda either as metioned Here.
Now that we have explained all of this and why it shouldn't really be done, it is time to remember that nothing is impossible in ruby so this would technically work:
def foo(string)
# place assignment in the guard clause
# because the empty return will result in `nil` a falsey value
return unless processed = method(:breaker).to_proc.call(string)
puts "This step should not be executed in the event of an error"
processed
end
def breaker(string)
begin
string.upcase!
rescue
puts "Well you messed that up, didn't you?"
return
end
string
end
Example
With Minitest Spec in Rails I'm trying to check if an ActiveSupport::TimeWithZone is in a certain range. I thought to use the between? method that takes the min and max of the range. Here's how I'm expressing that in Minitest Spec:
_(language_edit.curation_date).must_be :between?, 10.seconds.ago, Time.zone.now
but it gives me this error:
Minitest::UnexpectedError: ArgumentError: wrong number of arguments (1
for 2)
What am I doing wrong?
Looks like must_be is implemented as infect_an_assertion :assert_operator, :must_be
assert_operator
# File lib/minitest/unit.rb, line 299
def assert_operator o1, op, o2, msg = nil
msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op} #{mu_pp(o2)}" }
assert o1.__send__(op, o2), msg
end
What if you use assert directly?
Example:
class DateTest < ActiveSupport::TestCase
test "using assert with between? should work" do
a = 5.seconds.ago
assert a.between?(10.seconds.ago, Time.zone.now)
end
end
Thanks to radubogdan for showing me some of the code behind the must_be method. It looks like it's designed to be used with operators like this:
_(language_edit.curation_date).must_be :>, 10.seconds.ago
and a side-effect of this is it works with boolean methods that take one or no arguments, but not with methods that take more than one argument. I think I'm supposed to do this:
_(language_edit.curation_date.between?(10.seconds.ago, Time.zone.now)).must_equal true
Im testing if my method populate() returns a non-null value (which it does, it returns an integer > 0) but having troubles to correctly write it. I have:
describe House::Room do
describe '.populate' do
let(:info) {
$info = {"people"=>
{"name"=>"Jordan",
"last_name"=>"McClalister"}}
}
it 'should return an integer > 0' do
expect(House::Room.populate(info)).not_to eq(nil)
end
end
end
You'll need to change the let assignment to:
describe House::Room do
describe '.populate' do
let(:info) {"people"=>
{"name"=>"Jordan",
"last_name"=>"McClalister"}
}
it 'should return an integer > 0' do
expect(House::Room.populate(info)).not_to be(nil)
end
end
end
That should make your code work as you expect.
However, you could also use another matcher, like 'be_within' if you wanted to be more specific, or write several expect statements in the same test, like 'expect to be an integer', 'expect to be greater than 0', etc... There is no limit to the number of expect statements you can have in an 'it' block, the test will only pass if all of the expectations are fulfilled. (That said, I believe best practice would be to split it up into individual tests.)
When running a unit test, I'm expecting a method I am testing to return a nested array like this:
[
{:identifier=>"a", :label=>"a label",
:sublist=>[{:identifier=>"sublist z", :label=>"z sublist label"}, {:identifier=>" sublist w", :label=>"sublist w label"}]},
{:identifier=>"b", :label=>"b label",
:sublist=>[{:identifier=>"sublist y", :label=>"y sublist label"}]},
..]
What is the most elegant way to check if the array returned is what I expect it to be?
I'm using Minitest Spec if that makes any difference.
Btw, the order of elements does not matter and may vary.
Thx.
In this case, it would be ideal to write a custom matcher for minitest.
Here, is the code that you would need to add in the matcher.
def match_hash(h1, h2)
matched = false
h1.each do |ele|
h2.each do |ele2|
match_elements?(ele, ele2) ? (matched = true) : next
end
if !matched
return matched
end
end
matched
end
def match_elements?(ele, ele2)
if (ele[:identifier] != ele2[:identifier]) || (ele[:label] != ele2[:label])
return false
end
if ele.has_key?(:sublist) && ele2.has_key?(:sublist)
return match_hash(ele[:sublist], ele2[:sublist])
end
true
end
Write your custom matcher using this example
Then use match_hash in your test case to compare the two hashes.
NOTE: The above code has been tested in irb and it works perfectly.
My goal is to replace methods in the String class with other methods that do additional work (this is for a research project). This works for many methods by writing code in the String class similar to
alias_method :center_OLD, :center
def center(args*)
r = self.send(*([:center_OLD] + args))
#do some work here
#return something
end
For some methods, I need to handle a Proc as well, which is no problem. However, for the scan method, invoking it has the side effect of setting special global variables from the regular expression match. As documented, these variables are local to the thread and the method.
Unfortunately, some Rails code makes calls to scan which makes use of the $& variable. That variable gets set inside my version of the scan method, but because it's local, it doesn't make it back to the original caller which uses the variable.
Does anyone know a way to work around this? Please let me know if the problem needs clarification.
If it helps at all, all the uses I've seen so far of the $& variable are inside a Proc passed to the scan function, so I can get the binding for that Proc. However, the user doesn't seem to be able to change $& at all, so I don't know how that will help much.
Current Code
class String
alias_method :scan_OLD, :scan
def scan(*args, &b)
begin
sargs = [:scan_OLD] + args
if b.class == Proc
r = self.send(*sargs, &b)
else
r = self.send(*sargs)
end
r
rescue => error
puts error.backtrace.join("\n")
end
end
end
Of course I'll do more things before returning r, but this even is problematic -- so for simplicity we'll stick with this. As a test case, consider:
"hello world".scan(/l./) { |x| puts x }
This works fine both with and without my version of scan. With the "vanilla" String class this produces the same thing as
"hello world".scan(/l./) { puts $&; }
Namely, it prints "ll" and "ld" and returns "hello world". With the modified string class it prints two blank lines (since $& was nil) and then returns "hello world". I'll be happy if we can get that working!
You cannot set $&, because it is derived from $~, the last MatchData.
However, $~ can be set and that actually does what you want.
The trick is to set it in the block binding.
The code is inspired by the old Ruby implementation of Pathname.
(The new code is in C and does not need to care about Ruby frame-local variables)
class String
alias_method :scan_OLD, :scan
def scan(*args, &block)
sargs = [:scan_OLD] + args
if block
self.send(*sargs) do |*bargs|
Thread.current[:string_scan_matchdata] = $~
eval("$~ = Thread.current[:string_scan_matchdata]", block.binding)
yield(*bargs)
end
else
self.send(*sargs)
end
end
end
The saving of the thread-local (well, actually fiber-local) variable seems unnecessary since it is only used to pass the value and the thread never reads any other value than the last one set. It probably is there to restore the original value (most likely nil, because the variable did not exist).
One way to avoid thread-locals at all is to create a setter of $~ as a lambda (but it does create a lambda for each call):
self.send(*sargs) do |*bargs|
eval("lambda { |m| $~ = m }", block.binding).call($~)
yield(*bargs)
end
With any of these, your example works!
I wrote simple code simulating the problem:
"hello world".scan(/l./) { |x| puts x }
"hello world".scan(/l./) { puts $&; }
class String
alias_method :origin_scan, :scan
def scan *args, &b
args.unshift :origin_scan
#mutex ||= Mutex.new
begin
self.send *args do |a|
break if !block_given?
#mutex.synchronize do
p $&
case b.arity
when 0
b.call
when 1
b.call a
end
end
end
rescue => error
p error, error.backtrace.join("\n")
end
end
end
"hello world".scan(/l./) { |x| puts x }
"hello world".scan(/l./) { puts $& }
And found the following. The change of containment of the variable $& became inside a :call function, i.e. on 3-rd step before :call $& contains a valid value, but inside the block it becomes the invalid. I guess this become due to the singularity stack and variable restoration during the change process/thread context, because, probably, :call function can't access the :scan local state.
I see two variants: the first is to avoid to use global variables in the specific function redefinitions, and second, may to dig sources of ruby more deeply.