如何使用 rspec 和 Rails 4 检查记录是否保存在数据库中?

How to check if a record is saved in the database using rspec with Rails 4?

如何编写规范来检查用户注册成功后是否在数据库中创建了新记录?在 Rails 4 中使用 rspec 与水豚、工厂女郎和 database_cleaner 宝石。

我觉得这种情况很常见,应该很容易找到答案,但我无法在这里或通过 google 找到答案。

您可能想要 change matcher

您将执行如下操作:

expect { 
  post :create, :user => {:user => :attributes }
}.to change { User.count }

expect { 
  post :create, :user => {:user => :attributes }
}.to change(User, :count)

此代码表示:

期望运行宁这第一个代码块改变我在运行那个代码块时得到的值

并且在功能上等同于写作:

before_count = User.count
post :create, :user => {:user => :attributes }
expect(User.count).not_to eq(before_count)

既然你提到了水豚,那么我假设你想要一个功能规范,当然你需要更改细节以匹配你的应用程序

require 'rails_helper'
feature 'Users' do # or whatever
  scenario 'creating an account' do
    visit root_path
    click_link 'Sign Up'
    fill_in 'Name', with: 'User 1'
    fill_in 'Email', with: 'email@domain.com'
    fill_in 'Password', with: 'password'
    expect{
      click_button 'Sign up'
    }.to change(User, :count).by(1)
  end
end

由于你使用的是factorygirl,所以可以使用factorygirl来创建测试数据

FactoryGirl.define do
 factory :user do
  sequence(:name) { |n| "user #{n}" }
  sequence(:email) { |n| "sampleuser+#{n}@sampleuser.com" }
  password '123456789'
end end

您可以在任何需要用户记录的时候使用'FactoryGirl.create(:user)'。

为了测试你可以这样写规范

expect{
      post :create, {user: FactoryGirl.attributes_for(:user)}
    }.to change(User, :count).by(1)