我想用 RSpec 测试以下控制器
coupons_controller.rb:
class Api::V1::CouponsController < ApiController
def index
if params[:profile_id]
@coupons = Profile.find(params[:profile_id]).coupons
end
end
end
我想知道
1) 如何使用
FactoryBot
创建工厂 (spec/factories/profiles.rb
, coupons.rb
, coupon_profiles.rb
)
2)如何写
spec/controllers/coupons_controllers.rb
:
个人资料.rb
class Profile < ApplicationRecord
accepts_nested_attributes_for :coupon_profiles
end
优惠券.rb
class Coupon < ApplicationRecord
has_many :coupon_profiles
end
coupon_profile.rb
class CouponProfile < ApplicationRecord
belongs_to :coupon
belongs_to :profile
end
类似:
# spec/factories/profiles.rb
FactoryBot.define do
factory :profile, class: 'Profile', do
# ...
end
end
# spec/factories/coupons.rb
FactoryBot.define do
factory :coupon, class: 'Coupon' do
# ...
end
end
# spec/factories/coupon_profiles.rb
FactoryBot.define do
factory :coupon_profile, class: 'CouponProfile' do
coupon
profile
end
end
老实说,您最好的选择是查看 FactoryBot 的 GETTING_STARTED 自述文件——您想了解的所有内容都在其中,并附有示例。这是自述文件的一个光辉例子。 (注意在上面的示例中使用
class
,有使用字符串化类名而不是类常量有特定的性能原因)
对于您的控制器规格,您是否已查看过 RSpec 文档?尽管建议您使用更多的功能测试,例如请求规范而不是控制器规范。您应该能够执行以下操作:
describe 'coupons' do
subject { response }
shared_examples_for 'success' do
before { request }
it { should have_http_status(:success) }
end
describe 'GET /coupons' do
let(:request) { get coupons_path }
it_behaves_like 'success'
end
describe 'GET /coupons/:profile_id' do
let(:request) { get coupon_path(profile)
let(:profile) { coupon_profile.profile }
let(:coupon_profile) { create :coupon_profile }
it_behaves_like 'success'
end
end