以下是我的测试,一切正常。当我运行测试时,表单将在ui
中填充名称和图像。如果我在访问groups_path
时也测试在ui
中创建的用户名是否存在,测试也通过了。唯一的问题是group
没有被创建。我不知道我错过了什么。
我使用devise
进行身份验证
create_group_spec.rb
require 'rails_helper'
RSpec.describe 'Creating a group', type: :feature do
before :each do
user = User.create!(name: 'Test user', email: 'test@gmail.com', password: '123456',
password_confirmation: '123456')
login_as(user, scope: :user)
end
scenario 'adds a new group when name and image is entered' do
visit new_group_path
fill_in('Name', with: 'Sports')
attach_file('Icon', "#{Rails.root}/integration_test_image/test.jpg")
sleep(3)
click_on 'Create Group'
visit groups_path
expect(page).to have_content('Sports')
end
end
groups_controller.rb
def create
@group = Group.new(group_params)
@group.user = current_user
respond_to do |format|
if @group.save
format.html { redirect_to groups_url, notice: 'Group was successfully created.' }
format.json { render :show, status: :created, location: @group }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @group.errors, status: :unprocessable_entity }
end
end
end
private
def group_params
params.require(:group).permit(:name, :icon)
end
不要在工作时间睡觉。sleep x
实际上并不能保证你等待的东西实际上已经完成了——它只会使你的测试变慢,并且可能会出现问题。
require 'rails_helper'
RSpec.describe 'Creating a group', type: :feature do
before :each do
# You should be using fixtures or factories instead.
user = User.create!(name: 'Test user', email: 'test@gmail.com', password: '123456',
password_confirmation: '123456')
login_as(user, scope: :user)
end
scenario 'adds a new group when name and image is entered' do
visit new_group_path
fill_in('Name', with: 'Sports')
# use a block instead of sleep
# images should also go in /spec/support or /spec/fixtures
attach_file('Icon', Rails.root.join("/integration_test_image/test.jpg")) do
click_on 'Create Group' # no need to visit since it will redirect
expect(page).to have_content('Sports') # have_content waits for the page to load
end
end
end
我通过在click_on 'Create Group'
行之后添加sleep(1)
来修复它。我认为通过访问groups_path
,它甚至在group object
创建完成之前发生得太快,因此它在ui
中变得不可用,这是测试失败的原因。通过1s
延迟切换到页面确保对象完成创建,并且在页面呈现时可用,因此测试通过。