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

nuypyhwy  于 5个月前  发布在  Ruby
关注(0)|答案(1)|浏览(77)

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

it 'registers the user with the correct first_name' do

      visit new_user_registration_path

      within '#new_user' do
        fill_in 'user[first_name]', with: 'Foo'
        fill_in 'user[last_name]', with: 'Bar'
        fill_in 'user[email]', with: 'foo@bar'
        fill_in 'user[password]', with: 'password'
        click_button
      end
      user = User.find_by(email: 'foo@bar')
      expect(user.first_name).to eq('Foo')
    end
  end

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

jm81lzqq

jm81lzqq1#

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

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

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

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

相关问题