rspec - Rails –Testing named scopes: test scope results or scope configuration? -


how should rails named scopes tested? test results returned scope, or query configured correctly?

if have user class .admins method like:

class user < activerecord::base   def self.admins     where(admin: true)   end end 

i spec ensure the results expect:

describe '.admins'   let(:admin) { create(:user, admin: true) }   let(:non_admin) { create(:user, admin: false) }   let(:admins) { user.admins }    'returns admin users'     expect(admins).to include(admin)     expect(admins).to_not include(non_admin)   end end 

i know incurs hits database, didn't see other choice if wanted test scope's behaviour.

however, i've seen scopes being specced confirming they're configured correctly, rather on result set returned. example, like:

describe '.admins'   let(:query) { user.admins }   let(:filter) { query.where_values_hash.symbolize_keys }   let(:admin_filter) { { admin: true } }    'filters admin users'     expect(filter).to eq(admin_filter) # or other similar assertion   end end 

testing direct innards of query hadn't occurred me before, , on face value appealing me since doesn't touch database, no speed hit incurred.

however, makes me uneasy because:

  • it's making black-box test grey(er)
  • i have make assumption because configured way, i'll results business logic requires

the example i've used trivial perhaps i'd okay testing configuration, but:

  • where draw line , 'the content of named scope complex , requires result confirmation tests on , above scope configuration testing'? line exist or should it?
  • is there legitimate/well-accepted/'best practice' (sorry) way test named scopes without touching database, or @ least touching minimally, or unavoidable?
  • do use either of above ways test scopes, or other method entirely?

this question(s) bit similar testing named scopes rspec, couldn't seem find answers/opinions testing scope results vs scope configuration.

i think have described problem well, , best answer, in opinion - depends.

if scope trivial, run-of-the-mill where, order, etc. there no real need test activerecord or database make sure work - can safely assume have been correctly implemented, , test structure expect.

if, on other hand, scope (or query) compound, or uses advanced features in complex configuration, believe setting tests assert behavior, using real live database (which installed locally, small custom-tailored data set) can go long way in assuring code works.

it you, if , when decide change strategies (use cool new mysql feature, or porting postgresql), refactor safely, checking functionality robust.

this better way verify the sql string typed there...


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -