Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In RSpec, using let variable inside before :all block

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)

like image 668
Fabian Silva Avatar asked Oct 29 '13 22:10

Fabian Silva


People also ask

Where can a let Block be defined in RSpec?

Let variables Another way to define a variable in RSpec is to use the let syntax. The let method should be called inside an example group. The first argument is the name of a variable to define.

What is the difference between let and let in RSpec?

You can use let! to force the method's invocation before each example. The difference between let, and let! is that let! is called in an implicit before block. So the result is evaluated and cached before the it block.

What does before do in Ruby?

This runs the block of code once before each example. If you have 10 examples in an example group, then the before example code will run 10 times. The before example code, then the example, the before example code, then the example, and so on.

Does RSpec clean database?

I use the database_cleaner gem to scrub my test database before each test runs, ensuring a clean slate and stable baseline every time. By default, RSpec will actually do this for you, running every test with a database transaction and then rolling back that transaction after it finishes.


1 Answers

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.

like image 57
Romain Paulus Avatar answered Oct 12 '22 04:10

Romain Paulus