简体   繁体   中英

Debugging rails tests

Testing has been the thing I've avoided until I realized that with well written tests I can avoid having to enter console and running a string of commands over and over again. The big issue I'm having, however, is that when a test fails, I can't see much data to use to debug with. For example, when I'm testing models I need to see the models attributes, and I need to control when it's been built, created, and saved, and a way to detect these states. With rails fixtures and plain vanilla tests this is annoying to do.

How can I make debugging fixtures and rails tests easier? Is there a way to display more console-like information when a test fails? Which testing tools can I use to debug more easily? After all, debugging the tests themselves is a huge waste of time, and the biggest obstacle to using them in the first place.

Thanks!

Logging helps a lot to investigate and fix issues. Not only in test but also when you deploy it on production. You can log state of your models and other useful info. Also standard rails logging logs SQL that is send to the database so you can easily see what's going on there. SQL logging is on by default in dev and test and looks similar to this:

[2015-09-24 23:19:36 ledger DEBUG]:   [1m[36m (0.2ms)[0m  [1mBEGIN[0m
[2015-09-24 23:19:36 ledger DEBUG]:   [1m[35mSQL (2.1ms)[0m  INSERT INTO "projections_tags" ("ledger_id", "tag_id", "name", "authorized_user_ids") VALUES ($1, $2, $3, $4) RETURNING "id"  [["ledger_id", "ea9a68c5-c7c8-4964-b078-45bfc93d41ef"], ["tag_id", 9], ["name", "test"], ["authorized_user_ids", "{1}"]]
[2015-09-24 23:19:36 ledger DEBUG]:   [1m[36m (0.4ms)[0m  [1mCOMMIT[0m

I'm using log4r as a logging library since it gives more control over the log output.

I also don't like debugging but in some cases it really helps. In this case byebug is your friend.

And of corse rails console and rails dbconsole

Debugging your tests is not very different from debugging your code.

Rails already comes with byebug gem (uncomment it, if necessary):

group :development, :test do
  gem 'byebug'
end

Now you are ready to put

debugger

line anywhere in your code.

Byebug supports many additional features, which you can find here: https://github.com/deivid-rodriguez/byebug

Also check https://github.com/deivid-rodriguez/pry-byebug project which provides even better experience for debugging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM