Capybara + Rspec嵌套路线

时间:2013-04-04 18:54:09

标签: ruby-on-rails rspec capybara nested-resources

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

  

1)照片页面访问照片路径FactoryGirl之后可以访问照片   创建记录        ←[31mFailure /错误:←[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:在find'←[0m ←[36m # ./app/controllers/photos_controller.rb:14:in显示'←[0m←[36m#   ./spec/requests/photo_pages_spec.rb:34:在'←[0m

中的块(3级)

我的嵌套路线如下:

  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代码度过了几个令人沮丧的时间,希望将来它变得更容易。

1 个答案:

答案 0 :(得分:0)

您的问题是您创建了mountain,然后是photo,但它们没有关联!

请改为:

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