containing shared examples in spec/support/ and require files in that directory from spec/spec_helper.rb: Dir["./spec/support/**/*.rb"].sort.each { |f| require f}
rspec spec/models Use the rspec command to run your specs: bundle exec rspec To run only a subset of these specs: Run only specs for AccountsController bundle exec rspec spec/controllers/accounts_controller_spec.rb Run only a particular example bundle exec rspec spec/controllers/accounts_controller_spec.rb:21
means of quickly generating sample data called fixtures. A fixture is essentially a YAML-formatted file which helps create sample data. contacts.yml aaron: firstname: "Aaron" lastname: "Sumner" email: "[email protected]" john: firstname: "John" lastname: "Doe" email: "[email protected]"
data Factory Girl, an easy-to-use and easy-to-rely-on gem for creating test data without the brittleness of fixtures spec/factories/contacts.rb FactoryGirl.define do factory :contact do firstname "John" lastname "Doe" sequence(:email) { |n| "johndoe#{n}@example.com"} end end it "is invalid without a firstname" do contact = FactoryGirl.build(:contact, firstname: nil) expect(contact.errors[:firstname]).to include("can't be blank") end Example Usage
"is invalid without a firstname" do contact = FactoryGirl.create(:contact, firstname: nil) expect(contact.errors[:firstname]).to include("can't be blank") end it "is invalid without a lastname" do contact = FactoryGirl.create(:contact, lastname: nil) expect(contact.errors[:lastname]).to include("can't be blank") end it "is invalid without an email address" do contact = FactoryGirl.create(:contact, email: nil) expect(contact.errors[:email]).to include("can't be blank") end it "returns a contact's full name as a string" do contact = FactoryGirl.create(:contact, firstname: "Jane", lastnalastname: "Smith" ) expect(contact.name).to eq 'Jane Smith' end end
"assigns the requested contact to @user" do user = FactoryGirl.create(:user) get :show, id: user expect(assigns(:user)).to eq user end it "renders the :show template" do user = FactoryGirl.create(:user) get :show, id: user expect(response).to render_template :show end end end Testing GET requests Basic controller specs spec/controllers/contacts_controller_spec.rb
users" do smith = FactoryGirl.create(:user, lastname: 'Smith') jones = FactoryGirl.create(:user, lastname: 'Jones') get :index expect(assigns(:users)).to match_array([smith, jones]) end it "renders the :index template" do get :index expect(response).to render_template :index end end Testing GET requests Basic controller specs spec/controllers/contacts_controller_spec.rb