【问题标题】:Rails: testing custom classes with RSpecRails:使用 RSpec 测试自定义类
【发布时间】:2013-09-26 15:52:02
【问题描述】:

是的,我知道这个问题很傻,新手也很简单,但我还是想不通。 我创建了一个类(in app/minions/ 目录)来解析来自 3rd 方服务(如 google、twitter 等)的身份验证哈希。看起来像这样。

class AuthHash

  def initialize(hash)
    @hash = hash
    @provider = hash[:provider]
    @uid = hash[:uid]
    create_user_hash
  end

 def create_user_hash
   @user_hash = send("parse_hash_from_" << @hash[:provider], @hash)
 end

 def credentials
    {provider: @provider, uid: @uid}
 end

 def user_hash
    @user_hash
 end

 private

   # parse_hash_from_* methods here

end

我已将该目录添加到自动加载路径中,因此我可以在我的控制器中使用它。现在我想为它写一些测试。

我正在使用带有 FactoryGirl 的 RSpec 进行测试。因此,我首先向spec/factories/ 添加了一个名为auth_hashes.rb 的工厂,但我无法将哈希定义为工厂中的字段。 所以我把声明移到了spec/minions/auth_hash_spec.rb

require 'spec_helper'

describe AuthHash do
  before_each do
    auth_hash = AuthHash.new({:provider=>"google_oauth2",:uid=>"123456789",:info=>{:name=>"JohnDoe",:email=>"john@company_name.com",:first_name=>"John",:last_name=>"Doe",:image=>"https://lh3.googleusercontent.com/url/photo.jpg"},:credentials=>{:token=>"token",:refresh_token=>"another_token",:expires_at=>1354920555,:expires=>true},:extra=>{:raw_info=>{:id=>"123456789",:email=>"user@domain.example.com",:verified_email=>true,:name=>"JohnDoe",:given_name=>"John",:family_name=>"Doe",:link=>"https://plus.google.com/123456789",:picture=>"https://lh3.googleusercontent.com/url/photo.jpg",:gender=>"male",:birthday=>"0000-06-25",:locale=>"en",:hd=>"company_name.com"}}})
  end
end

但它似乎仍然不起作用。

我知道这应该比我尝试做的简单得多,但我无法弄清楚。

【问题讨论】:

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


    【解决方案1】:

    在顶部的新规范 (spec/minions/auth_hash_spec.rb) 文件中添加类似内容:

    require Rails.root.to_s + '/app/minions/myhash.rb'
    

    然后编写你的测试。

    【讨论】:

    • 我不能只添加require 'auth_hash',因为它在自动加载路径中吗?
    • 除非你设置 Rails 自动加载你的新目录,否则它不会自动加载它。参考这个。 stackoverflow.com/questions/4073856/rails-3-autoload
    • 您阅读我的评论和问题了吗?我这样做是为了自动加载。所以,是的,只是简单的要求似乎工作。但我认为应该有一种方法可以将原型声明从测试转移到某种工厂。
    • 我刚刚通过创建一个类并尝试实例化它来测试是否所有内容都自动加载到 /app 中。我不得不要求它来实例化这个类。所以在 Rails 3.2.13 的 /app 下没有自动加载所有内容。您使用的是以前版本的 Rails 吗?
    猜你喜欢
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多