ruby/rails 的新功能,目前正在学习和编写规范。我有这两种抓取 instagram 关注者的方法
def instagram_scraped_followers_count(instagram_username)
url = "https://www.instagram.com/#{ CGI::escape(instagram_username) }/"
body = HTTParty.get(url)
match = body.match(/(?<=content\=")(?<count>\d+[,.]?\d*)(?<unit>[km])?(?=\sFollowers)/) if body
match['count'].to_f * instagram_multiplier(match['unit']) if match
end
def instagram_multiplier(unit)
case unit
when 'm' then 1_000_000
when 'k' then 1_000
else 1
end
end
并为此添加了单元测试,如下所示:
context '1,300 followers' do
let(:html_body) { '<meta content="1,300 Followers, 1,408 Following, 395 Posts' }
it 'returns 1,300' do
expect(subject.stats[:instagram]).to eql(1_300.0)
end
end
我的单元测试失败是因为 context '1,300 followers' do
并且错误显示 expected: 1300.0 got: 1.0
我错过了什么?是因为 instagram_multiplier
方法没有条件吗?
最佳答案
match[:count].to_f
of 1,300
返回 1
。
我建议您将其更改为 match[:count].gsub(',', '').to_f
将 ,
替换为空,然后执行一个.to_f
def instagram_scraped_followers_count(instagram_username)
url = "https://www.instagram.com/#{ CGI::escape(instagram_username) }/"
body = HTTParty.get(url)
match = body.match(/(?<=content\=")(?<count>\d+[,.]?\d*)(?<unit>[km])?(?=\sFollowers)/) if body
match['count'].gsub(',', '').to_f * instagram_multiplier(match['unit']) if match
end
def instagram_multiplier(unit)
case unit
when 'm' then 1_000_000
when 'k' then 1_000
else 1
end
end
关于ruby-on-rails - 抓取 instagram 关注者的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56233520/