ruby-on-rails - 抓取 instagram 关注者的单元测试

标签 ruby-on-rails ruby

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/

相关文章:

ruby-on-rails - 如何开始测试 Rails 应用程序?

ruby-on-rails - 将对象添加到关联的集合而不保存

ruby-on-rails - 继承资源和CanCan 3层嵌套

Ruby 需要 'file' 和相对位置

javascript - rails : Paperclip gem no longer works after switching computers

ruby - 为什么我在此 Ruby 脚本中得到 "Test is not a class"?

ruby 将选定的整个单词括在括号中

ruby-on-rails - 如何替换 Ruby on Rails 中的默认 url/path REST 助手?

ruby-on-rails - 我可以在不提供显式外键的情况下测试嵌套资源吗?

ruby-on-rails - 如何在 Assets 管道中使用图标?