Rspec预计为零

时间:2015-10-14 09:46:20

标签: ruby-on-rails rspec

我尝试用Rspec测试我的控制器:

let(:valid_attributes) {
        FactoryGirl.attributes_for(:job)
    }

....

describe "GET #new" do
        it "assings a new job" do
            get :new
            expect(assigns(:job)).to be_a_new(Job)
        end
    end

我的工厂:

  FactoryGirl.define do
   factory :job do
    title "MyString"
    description "MyDescription"
    city "MyCity"
    date Date.today
    job_end false
    user
   end
  end

schema.rb:

create_table "jobs", force: :cascade do |t|
t.string   "title"
t.text     "description"
t.string   "city"
t.datetime "date"
t.datetime "created_at",  null: false
t.datetime "updated_at",  null: false
t.integer  "user_id"
t.boolean  "job_end"
end

和我得到的错误:

 Failure/Error: expect(assigns(:job)).to be_a_new(Job)
   expected nil to be a new Job(id: integer, title: string, description: text, city: string, date: datetime, created_at: datetime, updated_at: datetime, user_id: integer, job_end: boolean)

我明白我创建的Job对象是错误的?或者是什么?你能解释一下吗?

我的控制员:

  def new
    @job = current_user.jobs_given.build
  end

  def create
    @job = current_user.jobs_given.build(job_params)

    if @job.save
        redirect_to @job
    else
        render 'new'
    end
end

1 个答案:

答案 0 :(得分:3)

之所以会发生这种情况,是因为设备gem会将您的重定向到sign_in_path,因为您登录的用户不正确。您应该在控制器测试的顶部执行此操作:

before(:each) do
    request.env["devise.mapping"] = Devise.mappings[:user]
    sign_in FactoryGirl.create(:user)
end

更好的方法是创建登录方法并在每个控制器中调用它。请参见此处:https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-3-and-4-%28and-RSpec%29(控制器规范部分)