Stubbing Github模块进行测试

时间:2015-05-04 13:34:28

标签: ruby-on-rails ruby unit-testing

在我的gem中,我使用Github gem作为GitHub API。我创建了一个EachValidator来检查某些URL给定的持续性:

def validate_each(record, attribute, value)
  return if value.empty? and not opts[:presence]
  if check_github_url value
    repo_data = GithubStats::Parser.parse value
    begin
      Github.repos(user: repo_data[:username], repo: repo_data[:repo]).commits.all
    rescue Github::Error::NotFound => e
  p e
      record.errors[attribute] << error_message
    end
  else
    record.errors[attribute] << error_message
  end
end

如何存根 Github.repos方法返回具体值?是否为某些存根更改类(按我的意思做出响应)就足够了?我正在使用Mocha,但我无法弄清楚如何在这里使用。

编辑:

我在考虑:

# inside test class
def initialize
  Github.stubs(:repos).returns(what_i_want_to_put_here)
end

首先,在给定的参数的条件下返回良好的响应或引发异常,所以我需要以某种方式捕获参数。或者也许我应该提出测试用例的例外?那将是完美而简单的解决方案,但我没有给我任何测试,我是对的吗?

编辑2:

我尝试过类似的东西:

#test case class
def initialize param
  Github.stubs(:repos).returns({})
  Github.repos.stubs(:commits).returns({})
  Github.repos.commits.stubs(:all).returns({})
  super param
end

def test_method
  Github.repos.commits.stubs(:all).throws(Github::Error::NotFound.new({}))
  # do the real method
  validated_record = validate_github_url("https://github.com/puradawid/github_stats_notexisting") do |model, attr_name|
    model.errors.[].expects('<<').once
  end
end

但这是一个例外:

ArgumentError: uncaught throw #<Github::Error::NotFound:  :  >
    /home/dawid/.rvm/gems/ruby-2.1.5/gems/mocha-1.1.0/lib/mocha/thrower.rb:10:in `throw'
    /home/dawid/.rvm/gems/ruby-2.1.5/gems/mocha-1.1.0/lib/mocha/thrower.rb:10:in `evaluate'
    /home/dawid/.rvm/gems/ruby-2.1.5/gems/mocha-1.1.0/lib/mocha/return_values.rb:20:in `next'
    /home/dawid/.rvm/gems/ruby-2.1.5/gems/mocha-1.1.0/lib/mocha/expectation.rb:569:in `invoke'
    /home/dawid/.rvm/gems/ruby-2.1.5/gems/mocha-1.1.0/lib/mocha/mock.rb:296:in `method_missing'
    /home/dawid/.rvm/gems/ruby-2.1.5/gems/mocha-1.1.0/lib/mocha/class_method.rb:63:in `all'
    /home/dawid/github_stats/lib/validators/github_projects_url_validator.rb:8:in `validate_each'
    /home/dawid/github_stats/test/github_validator_test.rb:85:in `validate_github_url'
    /home/dawid/github_stats/test/github_validator_test.rb:45:in `block in <class:GithubStatsValidatorTest>'

在这里查看第一个代码。它正在捕捉Github::Error:NotFound所以这里的代码有什么问题?

1 个答案:

答案 0 :(得分:1)

尝试

Github.expects(:repos).returns(JSON.generate("Some Return Value"))

因此假设您期望API返回JSON,您可以

require 'json'

...

Github.expects(:repos).returns(JSON.generate({some: :hash}))