无需rails-controller-testing gem,如何用原生RSpec测试控制器赋值满足Simplecov?
原生RSpec实现方案
当然可以用原生RSpec做到,不需要额外安装任何gem。核心就是直接调用控制器的动作方法,然后验证实例变量的赋值情况。
测试代码示例:
RSpec.describe UsersController, type: :controller do describe '#new' do it 'assigns a new User instance to @user' do # 直接触发控制器的new动作 subject.new # 检查实例变量是否正确赋值 expect(assigns(:user)).to be_a_new(User) end end end
额外说明
assigns是RSpec自带的方法,专门用来访问控制器实例中的实例变量,不需要依赖rails-controller-testing。- 如果你确实觉得测试这种简单赋值没价值,也可以直接在Simplecov配置里跳过这类代码。比如在项目根目录的
.simplecov文件中添加过滤规则:
SimpleCov.start do # 跳过UsersController里的@user = User.new这行代码 add_filter do |source_file| source_file.filename.include?('users_controller.rb') && source_file.lines.any? { |line| line.content.strip == '@user = User.new' } end end
这样既不用写无意义的测试,也能保持覆盖率统计的“美观”。
内容的提问来源于stack exchange,提问作者Chad
相关产品推荐
相关产品推荐

