1

在我有嵌套资源的地方,我的 Capybara RSPEC 测试遇到了一些困难。这是我收到的错误:

1) 照片页面访问照片路径 FactoryGirl创建记录后可以访问照片←[31mFailure/Error:←[0m ←[31mvisit mountain_photo_path(mountain, photo)←[0m

 ←[31mActiveRecord::RecordNotFound:←[0m
   ←[31mCouldn't find Photo with id=1 [WHERE "photos"."mountain_id" = 1]←[0m

←[36m # C:in find'←[0m ←[36m # ./app/controllers/photos_controller.rb:14:inshow'←[0m ←[36m # ./spec/requests/photo_pages_spec.rb:34:in `block (3 levels) in '←[0m

我的嵌套路线如下:

  resources :mountains do
    resources :photos
  end

我正在我的 RSPEC 测试中测试以下内容:

require 'spec_helper'

describe "Photo pages" do
    let(:user) { FactoryGirl.create(:user)}
    let(:region) { FactoryGirl.create(:region)}
    let(:mountain) {FactoryGirl.create(:mountain)}
    let(:photo) {FactoryGirl.create(:photo)}

    before { sign_in user }

    describe "visit mountain path" do
        it "can be visited after FactoryGirl create" do
            visit mountain_path(mountain)
            page.should have_selector('h1', text: "Breck Test")
        end
    it "has the correct region associated to it" do
        visit mountain_path(mountain)
        page.should have_selector('h4', text: "Rockies")
    end
    end


    describe "visit photo path" do
        it "Photo can be visited after FactoryGirl create records" do
            visit mountain_photo_path(mountain, photo) 
            page.should have_selector('title', text: photo.name)
        end
    end

end

我相信 FactoryGirl 正在成功创建所有记录。Photo 上的附件是通过 CarrierWave 完成的,调试后相信这也可以正确加载。

include ActionDispatch::TestProcess

FactoryGirl.define do
  factory :user do
    first_name 'Test'
    last_name 'User'
    email 'example@example.com'
    password 'password1'
    password_confirmation 'password1'
    # required if the Devise Confirmable module is used
    confirmed_at Time.now
  end
  factory :region do
    name 'Rockies'
  end
  factory :mountain do
    name 'Breck Test'
    region {|a| a.association(:region)}
    description 'This is my testing mountain only'
  end
  factory :photo do 
    name 'My Photo Test'
    description 'My lovely description'
    mountain {|a| a.association(:mountain)}
    image { fixture_file_upload(Rails.root + 'spec/fixtures/files/breck.jpg', "image/jpeg")}
  end
end

我非常感谢这里小组的智慧,在此先感谢您的帮助。今天花了几个令人沮丧的时间来处理这个 rspec 代码,希望将来它会变得更容易。

4

1 回答 1

0

您的问题是您创建了 a mountain,然后创建了 aphoto但它们不相关!

改为这样做:

require 'spec_helper'

describe "Photo pages" do
  let(:user) { FactoryGirl.create(:user)}
  let(:region) { FactoryGirl.create(:region)}
  let(:mountain) { FactoryGirl.create(:mountain)}
  let(:photo)    { FactoryGirl.create(:photo, mountain: mountain) }

  before { sign_in user }

  describe "visit photo path" do
    it "Photo can be visited after FactoryGirl create records" do
      visit mountain_photo_path(photo.mountain, photo) 
      page.should have_selector('title', text: photo.name)
    end
  end
end
于 2013-04-04T19:36:39.133 回答