In RSpec, using let variable inside before :all block

半城伤御伤魂 提交于 2019-12-19 05:05:15

问题


I have the following code inside most of my tests:

describe 'index'
 let(:company) { FactoryGirl.create(:company) }
 let(:user) { FactoryGirl.create(:user, company: company) }

 before do
   sign_in user
   visit products_path
 end
...
end

But I'm getting the following warning:

WARNING: let declaration 'user' accessed in a 'before(:all)'

My question is, what is the correct way of doing this? I can't find much information about the warning itself.

Thanks!

EDIT: My goal is to use the user variable so I can pass it on to sign_in, which signs the user in, and use it later on another tests (I check for the company attribute of the User)


回答1:


I had the same problem, I have solved it by declaring all my variables as attributes inside the before block:

describe 'index'

 before(:all) do
   @company = FactoryGirl.create(:company)
   @user = FactoryGirl.create(:user, company: @company)

   sign_in @user
   visit products_path
 end
...
end

Now you can use @user and @company inside your tests, and you shouldn't have any warnings.




回答2:


I'm not sure what you mean by "this" in "what is the correct way of doing this"? Accessing let and subject within a before(:all) is deprecated and will be removed in RSpec 3 with the following explanation from https://github.com/rspec/rspec-core/pull/857:

let and subject declarations are not intended to be called in a before(:all) hook, as they exist to define state that is reset between each example, while before(:all) exists to define state that is shared across examples in an example group.




回答3:


Taking into account Peter's answer I think the correct way is to access the user in a before each block:

before(:each) do
  sign_in user
end


来源:https://stackoverflow.com/questions/19670375/in-rspec-using-let-variable-inside-before-all-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!