我是 Rails 的新手,我正在使用 capybara rspec 和 factory girl 测试我的设计 gem 用户。
这是规范代码:
require 'rails_helper'
RSpec.describe User, type: :request do
it "displays the user's email after successful login" do
user = FactoryGirl.create(:user, email: 'test@test.com', password: 'password')
visit root_url
fill_in 'Email', with: 'test@test.com'
fill_in 'Password', with: 'password'
click_button 'Log in'
expect page.has_content?('jdoe')
end
end
问题出在
expect page.has_content?('jdoe') No matter what i put instead 'jdoe' test works perfectly without any errors.
这是工厂:
FactoryGirl.define do
factory :user do
email 'test@test.com'
password 'password'
password_confirmation 'password'
end
end
也许我错过了什么或者走错了路。我应该如何在这里测试?
最佳答案
# spec/features/sessions_spec.rb
require 'rails_helper'
RSpec.feature "Sessions" do
scenario "displays the user's email after successful login" do
user = FactoryGirl.create(:user)
visit root_url
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Log in'
expect(page).to have_content("Signed in successfully")
# will give a false postitive if form is rerended?
expect(page).to have_content(user.email)
end
end
这里有几件事:
- 使用 feature而不是端到端测试的请求规范。
- 不要硬编码对象属性。工厂的全部意义在于工厂负责生成唯一数据,以便测试不会因残留状态而给出误报。
- 使用
expect(page).to
而不是expect page.should
。expect(page).to
设置主题并使用 RSpec 匹配器,如果不匹配,它将在错误消息中向您显示页面文本。
关于ruby-on-rails - 使用 capybara rspec 和工厂女孩测试设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40261459/