如何在shoulda_matches 2.0中弃用它时测试respond_with_content_type

时间:2013-09-12 09:19:30

标签: rspec rspec2 rspec-rails

respond_with_content_type匹配器现已弃用shoulda-matchers gem(版本> 2.0以及版本1.5.6中的大量丑陋警告)

Thoughtbot建议开发人员应该使用集成测试,但这并不总是在低资源项目上

所以问题是如何修复损坏的规格? ......或者如何替换它们

参考:

1 个答案:

答案 0 :(得分:1)

最简单的方法是将respond_with_content_type的任何匹配项替换为:

# spec/controllers/users_controller_spec.rb
describe UsersController do
  before{ get :index, :format => :xlsx }
  it 'response should be excel format' do
    response.content_type.to_s.should eq Mime::Type.lookup_by_extension(:xlsx).to_s
  end
end

如果你想要一个合适的匹配器:

# spec/support/matchers/respond_with_content_type_matchers.rb
RSpec::Matchers.define :respond_with_content_type do |ability|
  match do |controller|
    expected.each do |format|  # for some reason formats are in array
      controller.response.content_type.to_s.should eq Mime::Type.lookup_by_extension(format.to_sym).to_s
    end
  end

  failure_message_for_should do |actual|
    "expected response with content type #{actual.to_sym}"
  end

  failure_message_for_should_not do |actual|
    "expected response not to be with content type #{actual.to_sym}"
  end
end

# spec/spec_helper.rb
...
#ensure support dir is loaded
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}  
...

B.T.W。:如果你错过了匹配器should assign_to而不是现有的解决方案https://github.com/tinfoil/shoulda-kept-assign-to。 Gem只是一个简单的shoulda-matcher扩展模块