在控制器中创建记录后,可以使用Rspec进行属性测试。具体步骤如下:
bundle install
安装所需的依赖库:group :development, :test do
gem 'rspec-rails'
end
controllers/records_controller_spec.rb
。require 'rails_helper'
RSpec.describe RecordsController, type: :controller do
# ...
end
describe
块中,编写测试用例。可以使用before
块在每个测试用例执行前创建记录:RSpec.describe RecordsController, type: :controller do
describe 'POST #create' do
before do
post :create, params: { record: { attribute1: 'value1', attribute2: 'value2' } }
end
it 'creates a new record' do
expect(assigns(:record)).to be_a(Record)
expect(assigns(:record)).to be_persisted
end
it 'sets the correct attributes' do
expect(assigns(:record).attribute1).to eq('value1')
expect(assigns(:record).attribute2).to eq('value2')
end
end
end
在上述示例中,post :create
模拟了在控制器中创建记录的操作。然后,可以使用assigns
方法获取在控制器中创建的记录,并进行属性测试。
bundle exec rspec
Rspec将执行测试用例,并输出测试结果。
这样,就可以在控制器中创建记录后使用Rspec测试属性了。根据具体的业务需求,可以编写更多的测试用例来覆盖不同的情况。
领取专属 10元无门槛券
手把手带您无忧上云