ruby-on-rails – FactoryGirl,Rspec,let和before问题

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – FactoryGirl,Rspec,let和before问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我第一次使用这些工具.我已阅读文档,但是想在这里询问我正在试图实现的目标.

我有一组用户,我想测试一些可以在控制器规格中执行的操作.当每个用户被创建时,都有一组回调来创建关联的对象.

我想访问这些用户实例和该ActiveRecord类的关联对象.因此,例如,用户将有一组列表,以便我可以调用user1.lists.

另外,我想在顶部隔离这个设置,并使用我们的或前一个黑色.似乎只是这样打电话:

  1. # will test that get_count_for_list will return 5
  2. describe ApiController do
  3.  
  4. # why same name - seems really confusing!
  5. let(:user) { FactoryGirl.create(:user) }
  6. let(:user2) { FactoryGirl.create(:user2) }

不会调用相关联的回调.它是否正确?还是可能是时间问题?

我喜欢使用let和能够访问我的ExampleGroups(如user.id)中的这些对象的语法,但无法访问user.lists.目前我正在做的事情是:

  1. # will test that get_count_for_list will return 5
  2.  
  3. describe ApiController do
  4.  
  5. # why same name - seems really confusing!
  6. let(:user) { FactoryGirl.create(:user) }
  7. let(:user2) { FactoryGirl.create(:user2) }
  8. let(:user3) { FactoryGirl.create(:user3) }
  9.  
  10. before do
  11. FactoryGirl.create(:user2)
  12. FactoryGirl.create(:user3)
  13. end

但觉得必须有一个更好的方法.我是否创建了这两个用户

谢谢

编辑1

我在这里分离了有关的代码. global_id值是通过回调创建的.它在db中正确存在,可以通过相应的find_by_email进行访问,但使用user2 var不提供访问权限.

  1. require 'spec_helper'
  2.  
  3. # will test that get_count_for_list will return 5
  4. describe ApiController do
  5. # why same name - seems really confusing!
  6. let!(:user) { FactoryGirl.create(:user) }
  7. let!(:user2) { FactoryGirl.create(:user2) }
  8. let!(:user3) { FactoryGirl.create(:user3) }
  9.  
  10.  
  11.  
  12. before do
  13. session[:user_id]=user.id # works
  14. end
  15.  
  16. describe 'FOLLOW / UNFOLLOW options' do
  17. it 'shall test the ability to follow another user' do
  18. puts "user1: " + user.global_id.to_s # doesn't output anything
  19. u2=User.find_by_email('jo@jo.com') # corresponds to user2
  20. post :follow,:global_id => user2.global_id # doesn't work
  21. #post :follow,:global_id => u2.global_id #works
  22.  
  23.  
  24. u3=User.find_by_email('su@su.com')
  25. puts "user_3" + u3.global_id.to_s # outputs correct value
  26.  
  27. post :follow,:global_id => user3.global_id #doesn't work
  28. #post :follow,:global_id => u3.global_id # works
  29.  
  30.  
  31. post :unfollow,:global_id => user.following.sample(1)
  32. response.code.should eq('200')
  33. end
  34. end
  35. end

解决方法

检查rspec doc: https://www.relishapp.com/rspec/rspec-core/v/2-11/docs/helper-methods/let-and-let

请注意,let是惰性评估的:直到第一次调用它定义的方法时,它才被评估.你可以用let!在每个示例之前强制该方法调用.

换句话说,如果您使用let-factory-girl,则在let-variable调用之前不会创建一条记录.

正确的代码是:

  1. # will test that get_count_for_list will return 5
  2. describe ApiController do
  3.  
  4. # why same name - seems really confusing!
  5. let!(:user) { FactoryGirl.create(:user) }
  6. let!(:user2) { FactoryGirl.create(:user2) }

猜你在找的Ruby相关文章