[英]How to access the same DB data that Capybara uses
I have a very simple password reset form, which is just a text field to enter an email and a submit button. 我有一个非常简单的密码重置表单,它只是一个用于输入电子邮件和提交按钮的文本字段。
There are some client-side validations using JS, so I use the Capyabara JS driver when writing spec tests for it. 有一些使用JS的客户端验证,因此我在为它编写规格测试时使用Capyabara JS驱动程序。
This test just tests that a password reset token is added to the user's auth_info
table. 此测试仅测试是否将密码重置令牌添加到用户的auth_info
表中。
describe "password reset form", js: true do
let(:email) { "foo@example.com" }
# Create existing user with an email so we can reset it's password
let!(:user) { create(:user, email: email) }
before(:each) do
fill_in email_field, with: email
click_button reset_button
end
it "generates a new token" do
# `token` is definitely getting set properly when I pause it here
# with binding.pry and inspect the object using `user.reload`
# But when running the test it always shows up as `nil`
expect(user.reload.auth_info.token).to match(/[A-Fa-f0-9]{32}/)
end
end
As the comment notes, I know for a fact the token is getting properly set when I inspect it directly using binding.pry
. 正如评论所指出的,我知道当我直接使用binding.pry
检查令牌时,令牌已正确设置。 But RSpec and Capybara are seeing it as nil
, even after refreshing the model using reload
. 但是RSpec和Capybara认为它是nil
,即使在使用reload
刷新模型之后也是如此。
Is Capybara maintaining a different cache or something? 水豚保持着不同的缓存还是其他东西?
Thanks! 谢谢!
EDIT: Also tried different combinations of applying the reload
to the User
model as well as the AuthInfo
model, in case I needed to refresh the latter too 编辑:还尝试了将reload
应用于User
模型以及AuthInfo
模型的不同组合,以防万一我也需要刷新后者
You're using a JS capable browser which means click_button is asynchronous. 您正在使用具有JS功能的浏览器,这意味着click_button是异步的。 The result of this is you're executing click_button and then immediately checking for the token before the action triggered by the button has occurred. 结果是您正在执行click_button,然后在按钮触发的动作发生之前立即检查令牌。 You can verify this by putting sleep 5
before the expect
and the test should pass. 您可以通过在expect
和测试应该通过之前进入sleep 5
来验证这一点。 The correct way to make the test wait before the check is to use capybaras matchers to look for info on the page that changes once the click_button has completed, something like either of the following 使测试在检查之前等待的正确方法是使用capybaras匹配器在click_button完成后更改的页面上查找信息,类似于以下两种情况之一
expect(page).to have_text('text that appears after click_button has succeeded')
expect(page).to have_selector('div.abcde') #element that appears after click_button has succeeded
Those will make the test wait until the action has completed and then you can check for the token 这些将使测试等到操作完成后,然后您才能检查令牌
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.