rspec让方法+循环

时间:2012-03-16 03:07:48

标签: devise rspec2 omniauth

我无法在循环中运行我的rspec示例。

  describe "GET all providers" do
    let(:current_user) { Factory(:user) }

    [:twitter, :facebook, :google_oauth2].each do |provider|
      before :each do
        current_user.confirm!
        sign_in current_user

        request.env['devise.mapping'] = Devise.mappings[:user]
        request.env["omniauth.auth"] = OmniAuth.config.add_mock provider, {
          :uid => '123456789',
          :info => {
            :email => current_user.email
          }
        }
      end

      it 'should add the authorization' do            
        get provider # method to create the authorization
        authorization = Authorization.where(:provider => request.env["omniauth.auth"][:provider], :uid => request.env["omniauth.auth"][:uid]).first
        current_user.authorizations.should include authorization
      end
    end
  end

目前这些例子都通过了。但问题是尽管memoizing current_user方法,current_user是循环的每次迭代的新用户实例。所以,如果我为current_user.authorizations.count.should == 3添加测试,则会失败。

这变得不那么需要实际测试它,并且更加理解为什么它不能表现我的期望。不应该let(:current_user) { Factory(:user) }在所有示例中保留相同的用户实例吗?

1 个答案:

答案 0 :(得分:1)

以下是我提出的要点,可以帮助您理解letlet!https://gist.github.com/3489451

let会记住每个it示例中的返回值,但每次在示例中第一次调用时都会执行该块。

例如,如果您在current_user示例块中第一次调用it,则会执行{ Factory(:user) }块。在同一current_user示例块中的第二个或任何后续时间调用it不会执行{ Factory(:user) }块;记忆的返回值。