dchelimsky (owner)

Revisions

gist: 187258 Download_button fork
public
Public Clone URL: git://gist.github.com/187258.git
Embed All Files: show embed
things_controller.rb #
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
# all of these variations will pass the accompanying spec using stubble
 
class ThingsController
  def create
    @thing = Thing.new(params[:thing])
    if @thing.save
      render :action => 'index'
    else
      render :action => 'new'
    end
  end
end
 
#OR
 
class ThingsController
  def create
    @thing = Thing.create(params[:thing])
    if @thing.valid?
      render :action => 'index'
    else
      render :action => 'new'
    end
  end
end
 
#OR
 
class ThingsController
  def create
    @thing = Thing.new(params[:thing])
    begin
      @thing.save!
      render :action => 'index'
    rescue ActiveRecord::RecordInvalid
      render :action => 'new'
    end
  end
end
 
#OR (even though you would never do this)
 
class ThingsController
  def create
    begin
      @thing = Thing.create!(params[:thing])
      render :action => 'index'
    rescue ActiveRecord::RecordInvalid
      @thing = Thing.new(params[:thing])
      render :action => 'new'
    end
  end
end
things_controller_spec.rb #
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
# stubble lets you express controller specs like this. it gives you
# the right feedback every step of the way, telling you when the model
# is not being accessed at all and when it receives messages with the
# wrong arguments, but it does not bind you to particular patterns.
 
describe ThingsController do
  describe "POST create" do
    it "creates a new post" do
      stubbing(Thing, :params => {'these' => 'params'}) do
        post :create, :thing => {'these' => 'params'}
      end
    end
    
    it "redirects to index" do
      stubbing(Thing) do
        post :create
        response.should render_template('index')
      end
    end
    
    context "with invalid attributes" do
      it "re-renders the 'new' template" do
        stubbing(Thing, :as => :invalid) do
          post :create
          response.should render_template('new')
        end
      end
    
      it "assigns the newly created thing" do
        stubbing(Thing, :as => :invalid) do |thing|
          post :create
          assigns[:thing].should == thing
        end
      end
    end
  end
end