rspec and shoulda - complementary or alternatives?

纵然是瞬间 提交于 2019-11-30 07:19:05
Peter Brown

I have to argue against Chris's answer that they are alternatives. I use Shoulda and Rspec together in my Rails application, and they complement each other well.

This combo allows me to write concise one-line unit tests for recurring things like associations and validations, as well as the having the full rspec suite for more complex specs. You get the best of both worlds without any conflicts.

Check out the Shoulda README which shows how to install along side Rspec. It even says it provides "Test::Unit- and RSpec-compatible one-liners that test common Rails functionality. These tests would otherwise be much longer, more complex, and error-prone."

Edit (examples):

At the top of my specs, I always declare my Class relationship and validation tests which are concise and easy to read.

describe Component do

  context 'relationships' do
    it { should belong_to(:technology)}
    it { should have_many(:system_components) }
    it { should have_and_belong_to_many(:variables) }
    it { should have_many(:images).dependent(:destroy) }
    it { should have_many(:documents).dependent(:destroy) }
  end

  context 'validations' do
    it { should validate_presence_of(:make) }
    it { should validate_presence_of(:model) }
    it { should ensure_length_of(:name).is_at_most(100) }
    it { should validate_presence_of(:technology_id) }
  end
end

Then the rest of my spec will have more complex tests where I am using mocks and stubs which come from Rspec.

rspec and shoulda are alternatives to each other. I started with shoulda, as well, and moving to rspec is as simple as s/context/describe/, s/should/it/, and you're off to the races. rspec has a bunch of tricks, various integrations, and more complex matchers, so I'm using it more these days myself.

One of my initial frustrations was that it was nearly impossible to find a tutorial that didn't assume Rails and Cucumber. Don't overthink it - there's a lot you can do with it, but you don't have to have a monster of a solution in place before you can use it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!