我第一次使用这些工具.我已阅读文档,但是想在这里询问我正在试图实现的目标.
我有一组用户,我想测试一些可以在控制器规格中执行的操作.当每个用户被创建时,都有一组回调来创建关联的对象.
我想访问这些用户实例和该ActiveRecord类的关联对象.因此,例如,用户将有一组列表,以便我可以调用user1.lists.
另外,我想在顶部隔离这个设置,并使用我们的或前一个黑色.似乎只是这样打电话:
# will test that get_count_for_list will return 5 describe ApiController do # why same name - seems really confusing! let(:user) { FactoryGirl.create(:user) } let(:user2) { FactoryGirl.create(:user2) }
不会调用相关联的回调.它是否正确?还是可能是时间问题?
我喜欢使用let和能够访问我的ExampleGroups(如user.id)中的这些对象的语法,但无法访问user.lists.目前我正在做的事情是:
# will test that get_count_for_list will return 5 describe ApiController do # why same name - seems really confusing! let(:user) { FactoryGirl.create(:user) } let(:user2) { FactoryGirl.create(:user2) } let(:user3) { FactoryGirl.create(:user3) } before do FactoryGirl.create(:user2) FactoryGirl.create(:user3) end
谢谢
编辑1
我在这里分离了有关的代码. global_id值是通过回调创建的.它在db中正确存在,可以通过相应的find_by_email进行访问,但使用user2 var不提供访问权限.
require 'spec_helper' # will test that get_count_for_list will return 5 describe ApiController do # why same name - seems really confusing! let!(:user) { FactoryGirl.create(:user) } let!(:user2) { FactoryGirl.create(:user2) } let!(:user3) { FactoryGirl.create(:user3) } before do session[:user_id]=user.id # works end describe 'FOLLOW / UNFOLLOW options' do it 'shall test the ability to follow another user' do puts "user1: " + user.global_id.to_s # doesn't output anything u2=User.find_by_email('jo@jo.com') # corresponds to user2 post :follow,:global_id => user2.global_id # doesn't work #post :follow,:global_id => u2.global_id #works u3=User.find_by_email('su@su.com') puts "user_3" + u3.global_id.to_s # outputs correct value post :follow,:global_id => user3.global_id #doesn't work #post :follow,:global_id => u3.global_id # works post :unfollow,:global_id => user.following.sample(1) response.code.should eq('200') end end 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调用之前不会创建一条记录.
正确的代码是:
# will test that get_count_for_list will return 5 describe ApiController do # why same name - seems really confusing! let!(:user) { FactoryGirl.create(:user) } let!(:user2) { FactoryGirl.create(:user2) }