我不确定如何在以下的intersection.rb
中测试#create_arrintersection.rb
class Intersection
def initialize(xa1, ya1, xa2, ya2, xb1, yb1, xb2, yb2 )
@xa1 = xa1.to_i
@ya1 = ya1.to_i
@xa2 = xa2.to_i
@ya2 = ya2.to_i
@xb1 = xb1.to_i
@yb1 = yb1.to_i
@xb2 = xb2.to_i
@yb2 = yb2.to_i
end
# compare sizes
# both can't have the same size
def self.check_size?
rec1 = [(@xa2-@xa1).abs, (@ya2-@ya1).abs]
rec2 = [(@xb2-@xb1).abs, (@yb2-@yb1).abs]
rec1 == rec2 or rec1 == rec2.reverse
# rec1<<rec2.reverse
end
def self.create_arr(a, b, c, d)
(a..c).to_a.product((b..d).to_a)
end
...
end
intersection_spec.rb
require './spec_helper'
require './intersection.rb'
describe Intersection do
before do
# YES
@xa1 = 0.0
@ya1 = 0.0
@xa2 = 5.0
@ya2 = 5.0
@xb1 = 1.0
@yb1 = 1.0
@xb2 = 4.0
@yb2 = 4.0
@intersection = Intersection.new(@xa1, @ya1, @xa2, @ya2, @xb1, @yb1, @xb2, @yb2)
end
specify{ expect(@intersection.create_arr(@xa1, @ya1, @xa2, @ya2)).to eq [[0,0], [0,1], [0,2], [0,3], [0,4], [0,5], [1,0], [1,1], [1,2], [1,3], [1,4], [1,5], [2,0], [2,1], [2,2], [2,3], [2,4], [2,5], [3,0], [3,1], [3,2], [3,3], [3,4], [3,5], [4,0], [4,1], [4,2], [4,3], [4,4], [4,5], [5,0], [5,1], [5,2], [5,3], [5,4], [5,5]] }
end
这会给TypeError: can't iterate from Float
。
我能做的一种方法是改变@xa1 = (1.0).to_i
但是我在初始化中所做的事情变得毫无用处。
测试带参数的#create_arr
的最佳方法是什么?
答案 0 :(得分:0)
您将遇到的一个问题是您的create_arr方法是Intersection上的类方法。您遇到的问题可能与在类的实例上调用类方法有关。
我建议简要回顾一下Class&amp; amp;实例方法,以了解那里发生了什么。 RailsTips对差异进行了很好的探索。
要使用下面的create_arr方法,您可以调用Intersection.create_arr(...)而不是@ intersection.create_arr(...)。
class Intersection
...
def self.create_arr(a, b, c, d)
(a..c).to_a.product((b..d).to_a)
end
...
end
要将方法更改为实例方法,请删除自我。&#39;来自类中的方法声明。这样你就可以通过@ intersection.create_arr(...)在Intersection类的实例上调用create_arr。
class Intersection
...
def create_arr(a, b, c, d)
(a..c).to_a.product((b..d).to_a)
end
...
end
最后,要解决有关测试课程的其他问题。我建议使用&#39;它&#39;块和&#39;。应该&#39;澄清你的RSpec。我在下面列出了代码的示例重构。
class Intersection
...
#=> refactored to use arrays and ranges for 4 arguments, you could make this take range values as params to make this less tied to arrays of 4 objects.
def self.create_arr(args = [])
args[0..2].product(args[1..3])
end
...
end
require './spec_helper'
require './intersection.rb'
describe Intersection do
before do
@xa1 = 0.0
@ya1 = 0.0
@xa2 = 5.0
@ya2 = 5.0
@xb1 = 1.0
@yb1 = 1.0
@xb2 = 4.0
@yb2 = 4.0
@intersection = Intersection.new(@xa1, @ya1, @xa2, @ya2, @xb1, @yb1, @xb2, @yb2)
end
it 'creates an array of tuples' do
@expected_results = [[0,0], [0,1], [0,2], [0,3], [0,4], [0,5], [1,0], [1,1], [1,2], [1,3], [1,4], [1,5], [2,0], [2,1], [2,2], [2,3], [2,4], [2,5], [3,0], [3,1], [3,2], [3,3], [3,4], [3,5], [4,0], [4,1], [4,2], [4,3], [4,4], [4,5], [5,0], [5,1], [5,2], [5,3], [5,4], [5,5]]
@results = Intersection.create_arr([@xa1, @ya1, @xa2, @ya2])
@results.should eq(@expected_results)
end
end