在不加载Rails的情况下,在Rspec中存储设计“current_user”方法

时间:2013-01-26 15:50:43

标签: ruby-on-rails rspec

我无法将我的测试与Rails分离。例如,如何在下面的帮助器中存根调用current_user方法(来自Devise)?

助手模块:

module UsersOmniauthCallbacksHelper

  def socialmedia_name(account)
    name = current_user.send(account)['info']['name']
    name = current_user.name if name.blank?
    name
  end

end

测试

require_relative '../../app/helpers/users_omniauth_callbacks_helper.rb'

describe 'UsersOmniauthCallbacksHelper' do
  include UsersOmniauthCallbacksHelper

  describe '#socialmedia_name(account)' do
    it 'should return the users name listed by the social media provider when that name is provided' do

      #once I've done away spec_helper, this next line ain't gonna fly.
      helper.stub(:current_user) { FactoryGirl.create(:user, facebook:  {"info"=>{"name"=>"Mark Zuckerberg"}}) }

      socialmedia_name('facebook').should == "Mark Zuckerberg"
    end
  end
end

如何存根在类中使用的current_user方法?

如果我加载Rails,测试仍然可以保留helper.stub(:current_user)。但很自然,因为我没有加载spec_helper文件,所以现在不行。

2 个答案:

答案 0 :(得分:2)

对于测试模块,您最好的选择是将助手包含到测试类中,创建新实例,然后从那里存根方法。另外,您应该将更多的名称逻辑移动到模型中,这样您就不需要帮助程序了解send(account),并且返回它是一个散列,它具有散列(Law德米特)。我想要几乎所有的socialmedia_name方法都在模型中。例如:

describe 'UsersOmniauthCallbacksHelper' do
  let(:helper) do
    Class.new do
      include UsersOmniauthCallbacksHelper
      attr_accessor :current_user
    end.new
  end
  let(:user) { stub('user') }

  before do
    helper.current_user = user
  end

  describe '#socialmedia_name(account)' do
    it 'should return the users name listed by the social media provider when that name is provided' do
      # stub user here

      helper.socialmedia_name('facebook').should == "Mark Zuckerberg"
    end
  end
end

答案 1 :(得分:0)

这是我最终得到的结果(在根据Jim的推荐重构代码之前)。最重要的是,测试运行得非常快。这个助手可能会改变,但我会在我的工作中使用这种无轨道策略。

#spec/helpers/users_omniauth_callbacks_helper_spec.rb

require_relative '../../app/helpers/users_omniauth_callbacks_helper.rb'
require 'active_support/core_ext/string'

describe 'UsersOmniauthCallbacksHelper' do
  let(:helper) do
    Class.new do
      include UsersOmniauthCallbacksHelper
      attr_accessor :current_user
    end.new
  end

  describe '#socialmedia_name(account)' do
    it 'should return the users name listed by the social media provider when that name is provided' do
      helper.current_user = stub("user", :facebook =>{"info"=>{"name"=>"Mark Zuckerberg"}}) 
      helper.socialmedia_name('facebook').should == "Mark Zuckerberg"
    end

    it 'should return the current users name when the social media data does not provide a name' do
     helper.current_user = stub("user", name: "Theodore Kisiel", facebook: {"info"=>{}}) 
      helper.socialmedia_name('facebook').should == "Theodore Kisiel"
    end
  end
end