2016-08-25 8 views
-2

前にユーザーを作成するこんにちは、私はRSpecの(そして一般的にはユニットテスト)に新しいですし、次のメソッドをテストしたい:RSpecの:試験方法

class HelloController < ApplicationController 

    def hello_world 
    user = User.find(4) 
    @subscription = 10.00 
    render :text => "Done." 
    end 
end 

私はそうのようなRSpecのを使用しようとしています:

Describe HelloController, :type => :controller do 

    describe "get hello_world" do 

     it "should render the text 'done'" do 
     get :hello_world 
     expect(response.body).to include_text("Done.") 
     end 
    end 
    end 

このメソッドが正しく動作し、テストが完了していることを単にテストしたいと思います。テストを実行すると、次のエラーが発生します。

Failure/Error: user = User.find(4) 

ActiveRecord::RecordNotFound: 
    Couldn't find User with 'id'=4 

しかし、実行する前にそのIDを持つユーザーを正しく作成するにはどうすればよいですか。私は他のチュートリアルや質問をもとに次のことを試してみましたが、それは動作しません:

describe "get hello_world" do 
     let(:user) {User.create(id: 4)} 

      it "should render the text 'done'" do 
       get :hello_world 
       expect(response.body).to include_text("Done.") 
      end 
    end 

は、事前にありがとうございます。

+0

これを確認してくださいhttps://github.com/thoughtbot/factory_girl_rails –

答えて

1

本当にアクション(例:def hello_world)は特定のIDに依存する必要があります。したがって、簡単な代替方法はuser = User.lastを使用するか、user = User.find_by(name: "name")という名前でユーザーを見つけることができます。テストでは、アクションでUser.lastを使用している場合、任意のユーザーを作成します。

describe "get hello_world" do 
    let(:user) {User.create!} 

    it "should render the text 'done'" do 
    get :hello_world 
    expect(response.body).to include_text("Done.") 
    end 
end 

または名前で検索している場合は、その名前でユーザーを作成できます。

describe "get hello_world" do 
    let(:user) {User.create!(name: "name")} 

    it "should render the text 'done'" do 
    get :hello_world 
    expect(response.body).to include_text("Done.") 
    end 
end 

ご希望の場合は、こちらをご覧ください。

1

本当に 'user = User.find(4)'を使用するのですか?実際にそれを行うつもりなら、ユーザーのfindメソッドをスタブしてユーザーオブジェクトを返す必要があります。

it "should render the text 'done'" do 
    u = User.new #a new user, your test database is empty, so there's no user with id 4 
    User.stub(find: u) #stub the User's find method to return that new user 
    get :hello_world 
    expect(response.body).to include_text("Done.") 
end 

別のオプションは、とにかくのparams

it "should render the text 'done'" do 
    u = User.create(.... your user params) 
    get :hello_world, user_id: u.id 
    expect(response.body).to include_text("Done.") 
end 

def hello_world 
    user = User.find(params[:user_id]) 
    @subscription = 10.00 
    render :text => "Done." 
end 

経由のuser_idを送信することで、私は、ハードコードidが悪いです、あなたはそれを行うべきであるとは思いません符号。ユーザーの登録とログインを制御する必要がある場合は、Deviseのようなものを使うことができますし、スペックの前にユーザーをログインする必要があるかもしれません。