Rails:使用 RSpec 测试命名范围 [英] Rails: Testing named scopes with RSpec

查看:27
本文介绍了Rails:使用 RSpec 测试命名范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是测试 Rails Web 应用程序和 RSpec 的新手.我使用遗留代码并需要添加测试.那么使用 RSpec 测试查找器和命名范围的最佳方法是什么?

I am new to testing Rails web applications and RSpec. I work with legacy code and need to add tests. So what is the best way to test finders and named scopes with RSpec?

我在 Google 中找到了一些方法,但它们并不理想.例如:

I find in Google a few approaches but they are not ideal. For example:

http://paulsturgess.co.uk/articles/show/93-using-rspec-to-test-a-named_scope-in​​-ruby-on-rails

it "excludes users that are not active" do
    @user = Factory(:user, :active => false)
    User.active.should_not include(@user)
end

http://h1labs.com/notebook/2008/8/21/testing-named-scope-with-rspec

it "should have a published named scope that returns ..." do
  Post.published.proxy_options.should == {:conditions => {:published => true}}
end

我在铁路测试处方"中找到了最佳方法(恕我直言):

I find best approach (IMHO) in "Rail Test Prescriptions":

should_match_find_method :active_only { :active == true }

where should_match_find_method 自定义辅助方法

where should_match_find_method custom helper method

推荐答案

RSpec 的创建者最近在博客上发表了他认为 验证是行为,关联是结构.换句话说,他发现关联(和范围)不应该被直接测试.这些测试将根据您想要的行为进行.

The creator of RSpec has recently blogged he thinks Validations are behavior, associations are structure. In other words he finds that associations (and scopes) should not nessesarily be tested directly. Tests for these will follow from the behavior you want.

换句话说,目前的观点是无需直接测试每个作用域,因为您将通过测试应用程序的行为来覆盖这些关联.

In other words, current wisdom is that there is no need to test each scope directly, since you will cover these associations by testing the behavior of your application.

这篇关于Rails:使用 RSpec 测试命名范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆