File: rspec-set.rb

package info (click to toggle)
ruby-rspec-set 0.1.3-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 128 kB
  • sloc: ruby: 246; makefile: 4
file content (57 lines) | stat: -rw-r--r-- 1,603 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
require "version"

module RSpec
  module Core
    module RSpecSet
      module ClassMethods
        # Set @variable_name in a before(:all) block and give access to it
        # via let(:variable_name)
        #
        # Example:
        #
        #   set(:transaction) { Factory(:address) }
        #
        #   it "should be valid" do
        #     transaction.should be_valid
        #   end
        #
        def set(variable_name, &block)
          before(:all) do
            # Create model
            self.class.send(:class_variable_set, "@@__rspec_set_#{variable_name}".to_sym, instance_eval(&block))
          end

          before(:each) do
            model = send(variable_name)

            if model.is_a?(ActiveRecord::Base)
              if model.destroyed?
                # Reset destroyed model
                self.class.send(:class_variable_set, "@@__rspec_set_#{variable_name}".to_sym, model.class.find(model.id))
              elsif !model.new_record?
                # Reload saved model
                model.reload
              end
            else
              warn "#{variable_name} is a #{model.class} - rspec-set works with ActiveRecord models only"
            end
          end

          define_method(variable_name) do
            self.class.send(:class_variable_get, "@@__rspec_set_#{variable_name}".to_sym)
          end
        end # set()

      end # ClassMethods

      def self.included(mod) # :nodoc:
        mod.extend ClassMethods
      end
    end # RSpecSet

    class ExampleGroup
      include RSpecSet
    end # ExampleGroup

  end # Core
end # RSpec