ruby-on-rails 当使用capybarra运行系统测试时,如何测试持久层?

nuypyhwy  于 2024-01-09  发布在  Ruby
关注(0)|答案(1)|浏览(159)

我在一个rails应用程序上工作,用户可以在那里注册。
一旦用户注册,我想检查持久化的用户记录是否符合某些期望,例如:名字已经保存。

  1. it 'registers the user with the correct first_name' do
  2. visit new_user_registration_path
  3. within '#new_user' do
  4. fill_in 'user[first_name]', with: 'Foo'
  5. fill_in 'user[last_name]', with: 'Bar'
  6. fill_in 'user[email]', with: 'foo@bar'
  7. fill_in 'user[password]', with: 'password'
  8. click_button
  9. end
  10. user = User.find_by(email: 'foo@bar')
  11. expect(user.first_name).to eq('Foo')
  12. end
  13. end

字符串
在上面的例子中,user是nil,因为注册请求还没有时间完成。我考虑了不同的选项:
1.仅在处理系统测试时使用expect(page)
1.玩page.document.synchronize并等待用户可用
1.使用“变通办法”使用每个示例的特异性(例如:使用User.last
我的理解是,我应该坚持使用选项1,但有时用户操作会产生无法在页面上呈现的效果。
你认为最好的解决办法是什么?

jm81lzqq

jm81lzqq1#

我这样做似乎是可靠的,如果你的表单正在创建一个用户,你可以这样做:

  1. expect{click_button}.to change{User.count}.by(1)
  2. user = User.find_by(email: 'foo@bar')
  3. expect(user.first_name).to eq('Foo')

字符串
如果你的表单正在编辑一个用户,你可以这样做:

  1. user = User.find_by(email: '[email protected]')
  2. expect{click_button}.to change{user.first_name}.to('Foo')

相关问题