ruby-on-rails - 使用 capybara rspec 和工厂女孩测试设计

标签 ruby-on-rails ruby testing rspec devise

我是 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

这里有几件事:

  1. 使用 feature而不是端到端测试的请求规范。
  2. 不要硬编码对象属性。工厂的全部意义在于工厂负责生成唯一数据,以便测试不会因残留状态而给出误报。
  3. 使用 expect(page).to 而不是 expect page.shouldexpect(page).to 设置主题并使用 RSpec 匹配器,如果不匹配,它将在错误消息中向您显示页面文本。

关于ruby-on-rails - 使用 capybara rspec 和工厂女孩测试设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40261459/

相关文章:

testing - 更改请求钩子(Hook)中的请求 URL

python - 如何测试处理设置文件所有权而不是 root 的函数

testing - 通过 Selenium WebDriver 在浏览器的同一窗口 session 中打开一个新选项卡?

ruby-on-rails - 在多个端口上运行 Rails 应用程序

ruby-on-rails - 自动测试失败, gem 规范无效

ruby-on-rails - 在 Rails ActiveRecord 中,连接不适用于命名空间模型中的 has_and_belongs_to_many

ruby-on-rails - 在 RSpec 2 中动态生成共享示例?

sql - 使用 Postgres 限制 Rails 中的 SQL 结果

ruby-on-rails - Rails : NoMethodError, 如何显示用户配置文件?

ruby - Ruby 中有类似 null-stream 的东西吗?