Rails测试current_path无法正常工作

时间:2014-07-19 01:35:32

标签: ruby-on-rails rspec

由于测试与正确的url路径不匹配,我的rspec测试失败。但是,当我在浏览器中手动检查它时,它可以正常工作。

我的测试看起来像:

require 'spec_helper'

feature "Photography jobs" do

    context "as a user" do

        scenario "adds a new photography job" do
            user = create(:user)
            signin(user.email, user.password)
            visit root_path
            click_link "Add Job"

            fill_in "Name", with: "Joe Blow"
            fill_in "Email", with: "joe@hotmail.com"
            fill_in "Session Date", with: "9/24/1978"
            fill_in "Location", with: "North Shore"
            fill_in "Notes", with: "Requested this date."
            click_button "Submit"

            expect(current_path).to eq job_path
            expect(page).to have_content "Session was successfully created."
            expect(page).to have_content "North Shore"
            expect(page).to have_content "9/24/1978"
        end

    end

end

控制器看起来像:

    def new
      @job = Job.new
    end

    def create
      @job = Job.new(job_params)
      @job.user = current_user
      if @job.save
        redirect_to @job, notice: 'Session was successfully created.' 
      else
        flash[:error] = @job.errors.full_messages
        flash[:errors_list] = @job.errors.messages
        redirect_to new_job_path(@job)
      end  
    end

运行rspec spec / features时出错:

 1) Photography jobs as a user adds a new photography job
     Failure/Error: expect(current_path).to eq job_path
     ActionController::UrlGenerationError:
       No route matches {:action=>"show", :controller=>"jobs"} missing required keys: [:id]
     # ./spec/features/new_jobs_spec.rb:20:in `block (3 levels) in <top (required)>'

1 个答案:

答案 0 :(得分:2)

这一行错了:

expect(current_path).to eq job_path

它必须类似于job_path(@job),但由于您正在使用submit创建新的工作记录,因此您无法在此执行此测试,因为工作记录没有:id直到它保存在您的数据库中。

我认为在控制器规范中进行这种测试是好的,但在功能规范中。 对于此处的功能规格,只需

click_button "Submit"

expect(page).to have_content "Session was successfully created."
expect(page).to have_content "North Shore"
expect(page).to have_content "9/24/1978"

很好。