Best practice for code reuse in rspec?

I am writing integration tests using Rspec and Capybara. I noticed that quite often I have to execute the same code snippets when it comes to testing the creation of activerecord parameters.

For instance:

it "should create a new instance" do
  # I create an instance here
end

it "should do something based on a new instance" do
  # I create an instance here
  # I click into the record and add a sub record, or something else
end

The problem is that ActiveRecord objects are not saved in tests, however Capybara by default supports the same session in the specification (weirdness).

I could mock these entries, but since this is an integration test, and some of these entries are quite complex (they have image attachments and much more), it’s much easier to use Capybara and fill out forms that appeal to the user.

, , - . ?

+3
5

. , , :

describe "your instance" do
  it "..." do
    # do stuff here
  end

  it "..." do
    # do other stuff here
  end
end

, , :

describe "your instance" do
  # run before each example block under the describe block
  before(:each) do
    # I create an instance here
  end

  it "creates a new instance" do
    # do stuff here
  end

  it "do something based on a new instance" do
    # do other stuff here
  end
end

before (: each) let helper, . .

+8

- Factory Girl , database_cleaner, /.

(, ) , . , --order rand rspec. , .

+6

(... Rspec), RSpec " Ruby on Rails",.

:

  • (, )

, .

( ) FactoryGirl.

+2

. : https://github.com/lucassus/locomotive

  • factory_girl
  • ( spec/support)
  • shared_examples
  • , , toa-macros
+1

factory_girl Rspec let:

describe User do
  let(:user) { create :user } # 'create' is a factory_girl method, that will save a new user in the test database

  it "should be able to run" do
    user.run.should be_true
  end

  it "should not be able to walk" do
    user.walk.should be_false
  end
end


# spec/factories/users.rb
FactoryGirl.define do
  factory :user do
    email { Faker::Internet.email }
    username { Faker::Internet.user_name }
  end
end

:

describe User do
  let(:user) { create :user, attributes }
  let(:attributes) { Hash.new }

  it "should be able to run" do
    user.run.should be_true
  end

  it "should not be able to walk" do
    user.walk.should be_false
  end

  context "when user is admin" do
    let(:attributes) { { admin: true } }
    it "should be able to walk" do
      user.walk.should be_true
    end
  end
end
0

All Articles