如何在Ruby2.5.0+Rails5项目中用RSpec与Factory Girl做测试?
用RSpec + Factory Bot 测试你的Token校验API
第一步:配置测试依赖
首先得把测试相关的Gem装起来,在你的Gemfile里的:development和:test组里加上这些:
group :development, :test do gem 'rspec-rails' gem 'factory_bot_rails' # 就是你说的Factory Girl,现在官方改名叫Factory Bot啦 end
然后跑一下bundle install,接着初始化RSpec的配置文件:
rails generate rspec:install
第二步:创建User测试工厂
在spec/factories/users.rb里定义User的工厂,方便快速生成测试用的用户数据:
FactoryBot.define do factory :user do email { Faker::Internet.email } # 用Faker生成随机邮箱,也可以写固定值 token { SecureRandom.uuid } # 生成随机token,测试时也能自定义 end # 如果需要固定的账号密码做测试,可以加个工厂变体 factory :fixed_user, parent: :user do email { 'test_user@example.com' } token { 'valid-test-token-123' } end end
要是想用Faker生成更真实的测试数据,记得在Gemfile里加gem 'faker', group: :test再跑一遍bundle install。
第三步:编写API请求测试
在spec/requests/check_token_spec.rb里写测试用例,覆盖所有可能的场景:
require 'rails_helper' RSpec.describe 'Token校验API', type: :request do describe 'POST /check_token' do context '传入正确的用户名和token时' do let(:valid_user) { create(:fixed_user) } it '返回200状态码' do post '/check_token', params: { username: valid_user.email, token: valid_user.token } expect(response).to have_http_status(200) end end context '用户名错误时' do let(:valid_user) { create(:fixed_user) } it '返回401状态码' do post '/check_token', params: { username: 'wrong_email@example.com', token: valid_user.token } expect(response).to have_http_status(401) end end context 'token错误时' do let(:valid_user) { create(:fixed_user) } it '返回401状态码' do post '/check_token', params: { username: valid_user.email, token: 'wrong-token-456' } expect(response).to have_http_status(401) end end context '服务器抛出异常时' do it '返回500状态码' do # 模拟User查询时抛出异常 allow(User).to receive(:where).and_raise(StandardError) post '/check_token', params: { username: 'any@example.com', token: 'any-token' } expect(response).to have_http_status(500) end end end end
另外记得在rails_helper.rb里加一行配置,让RSpec自动识别Factory Bot的语法:
RSpec.configure do |config| config.include FactoryBot::Syntax::Methods end
第四步:运行测试
在终端里执行命令跑测试就行:
# 只跑这个API的测试 rspec spec/requests/check_token_spec.rb # 跑所有RSpec测试 rspec
内容的提问来源于stack exchange,提问作者awsm sid
相关产品推荐
相关产品推荐

