问题
I have the given testing code:
describe 'A new user', js: true do
before do
@new_user = Fabricate.build(:user)
end
it 'should sign up' do
#login code
visit '/'
click_link 'Login'
fill_in 'user[email]', :with => @new_user.email
fill_in 'user[password]', :with => @new_user.password
click_button 'Login now'
#login code end
page.should have_content("Hello #{@new_user.first_name}!")
current_path.should == dashboard_path
end
it 'should receive a confirmation mail' do
#same login code again
visit '/'
click_link 'Login'
fill_in 'user[email]', :with => @new_user.email
fill_in 'user[password]', :with => @new_user.password
click_button 'Login now'
mail = ActionMailer::Base.deliveries.last
assert_equal @new_user.email, mail['to'].to_s
end
end
Now I want to add more tests. To avoid code doubling, how can I run the capybara login code once before all tests? One solution would be to put the login code in the before method. Another would be to create a method do_login, put the code in it and run every test like this:
it 'should do something after login' do
do_login
#test code here
end
But for both solutions, the code is run for every test and thats not what I want. Putting the login code in a before(:all)
doesn't work, too.
How can I run some capybara code once and then do all the tests after this?
回答1:
You can't run capybara code once and then run all the tests. You always start from scratch. Your proposed solution with before(:each) or helper method is the only posibility. (It's possible to run some ruby before(:all) e.g. create objects outside the transaction check here but not Capybara)
To speed up your specs you can test login feature in separate spec and then somehow stub the authentication but it depends on your implementation.
If you are using Devise check devise wiki: https://github.com/plataformatec/devise/wiki/How-To:-Controllers-tests-with-Rails-3-(and-rspec)
来源:https://stackoverflow.com/questions/12371605/how-to-run-capybara-commands-once-then-run-some-tests