Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does testing Rails 3 Scopes make sense?

I'm a little torn. Do unit tests for Scopes in Rails 3 make sense?

On the one hand, I'm writing code and I should test that code.

However, on the other hand, basically all my scopes are effectively trivial. Checking one variable against a passed parameter is pretty much the most complex scope I have so far.

scope :author, proc { |author| where(:author_user_id => author }

That code is trivial and also more or less covered in the functions that actually USE the scopes.

What are the best practices for testing or not testing scopes?

like image 360
Drew Avatar asked Sep 01 '11 03:09

Drew


People also ask

Why do we use scope in Rails?

Scopes are used to assign complex ActiveRecord queries into customized methods using Ruby on Rails. Inside your models, you can define a scope as a new method that returns a lambda function for calling queries you're probably used to using inside your controllers.

What type of test is not typical in a Rails application?

Don't write route tests, except if you're writing an API, for the endpoints not already covered by integration tests. Don't write view tests. You should be able to change copy or HTML classes without breaking your tests. Just assess critical view elements as part of your in-browser integration tests.

What are scopes Rails?

Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.


2 Answers

David Chelimsky (Rspec's creator) offered up the following example in the Rspec Google Group:

describe User, ".admins" do 
  it "includes users with admin flag" do 
    admin = User.create! :admin => true 
    User.admin.should include(admin) 
  end

  it "excludes users without admin flag" do 
    non_admin = User.create! :admin => false 
    User.admin.should_not include(non_admin) 
  end 
end

class User < ActiveRecord::Base 
  named_scope :admins, :conditions => {:admin => true} 
end 

It's obviously not the same example as yours, but it should give you an idea of how to do it. The relevant thread for context is here: http://groups.google.com/group/rspec/browse_thread/thread/6706c3f2cceef97f

like image 173
BvuRVKyUVlViVIc7 Avatar answered Sep 18 '22 05:09

BvuRVKyUVlViVIc7


If you think the scope is too simple to be tested, you can surely ignore it, but if you are thinking about testing scopes I'd tell you to look at this answer and focusing on testing behavior and not code itself.

like image 20
Maurício Linhares Avatar answered Sep 18 '22 05:09

Maurício Linhares