2012-03-16 86 views
2

我无法在循环中运行我的rspec示例。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 

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

这变得不那么需要实际测试它,并更多地了解为什么它不符合我的期望。 let(:current_user) { Factory(:user) }是否应该在所有示例中保留相同的用户实例?

回答

1

这里是我想出了一个要点可以帮助你了解letlet!https://gist.github.com/3489451

let memoizes每个it例子中的返回值,但每次调用的首次时间执行该块在这个例子中。

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

+0

谢谢你的回答。在你说这是这句话之前,我不清楚什么: 'let'记住每个'it'示例中的返回值,但是在示例中每次第一次调用它时都会执行该块。 – Francois 2016-10-05 08:32:34