我试图让我的网络应用程序的用户能够使用密码登录。我正在滚动自己的身份验证,而不是使用 gem。我读了这篇关于重构 Rspec/Capybara 测试的文章:
http://robots.thoughtbot.com/rspec-integration-tests-with-capybara
我喜欢我读到的内容,并决定尝试重构。我为功能测试创建了一个 session 帮助程序文件。
module Features
module SessionHelpers
def sign_in
user = create(:user)
visit '/authentications/new'
fill_in 'Login', with: user.name
fill_in 'Password', with: user.password
click_button 'Sign in'
end
end
end
然后我在登录测试中调用了sign_in函数。这是一个小示例。
require 'spec_helper'
feature "signing in" do
before :each do
User.create(:name => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="433630263103263b222e332f266d202c2e" rel="noreferrer noopener nofollow">[email protected]</a>', :password => 'caplin')
end
scenario "user who logs in with correct credentials" do
sign_in
expect(page).to have_content 'Hi <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8afff9eff8caeff2ebe7fae6efa4e9e5e7" rel="noreferrer noopener nofollow">[email protected]</a>'
end
end
不幸的是,我不断收到此错误消息:
2) signing in user who logs in with correct credentials
Failure/Error: sign_in
NoMethodError:
undefined method `create' for #<RSpec::Core::ExampleGroup::Nested_3:0x007ffc85012438>
# ./spec/support/features/session_helpers.rb:4:in `sign_in'
# ./spec/features/user_logs_in_spec.rb:13:in `block (2 levels) in <top (required)>'
基本上,我需要某种方法来获取我创建的用户并将其传递到sign_in函数中。有什么提示吗?
最佳答案
我猜您的第一个问题是与 ThoughBot 示例不同的测试配置。据我所知,create
并不是 RSpec 中可用的默认方法;我猜他们已经将所有 FactoryGirl 方法添加到测试范围中。如果您使用 FactoryGirl,只需为创建命令命名空间即可获得相同的行为:
def sign_in
user = FactoryGirl.create(:user)
visit '/authentications/new'
fill_in 'Login', with: user.name
fill_in 'Password', with: user.password
click_button 'Sign in'
end
但是,这并不能完全满足您所要求的一切,因为您仍然无法添加自定义用户。一个简单的方法是允许用户传入:
def sign_in(user=nil)
user ||= FactoryGirl.create(:user)
...
end
如果您没有在 sign_in
调用中传递用户,这将为您创建用户。
回到您发布的规范,您希望将其更改为:
feature "signing in" do
before :each do
@user = User.create(:name => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5025233522103528313d203c357e333f3d" rel="noreferrer noopener nofollow">[email protected]</a>', :password => 'caplin')
end
scenario "user who logs in with correct credentials" do
sign_in(@user)
expect(page).to have_content 'Hi <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99c9a8c9ba98c91888499858cc78a8684" rel="noreferrer noopener nofollow">[email protected]</a>'
end
end
您需要将创建的用户附加到变量 (@user
),然后根据需要将其传递给 sign_in
。
关于ruby-on-rails - Rails 4 中 rspec 功能测试的重构代码出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20390072/