简体   繁体   中英

RSPEC view testing with associated methods

How do I implement methods provided through an ActiveRecord association using Factory Girl and RSPEC? The code is working as I want it to, but I am unable to create a functional view test.

The scenario is a 'user' that has many 'pics'. There is a Carrierwave uploader associated with 'pic' named 'photo'.

Controller:

@users = User.includes(:pics).order("pics.pic_order ASC")

View:

<% @users.each do |user| %>
  <%= image_tag(user.pics.first.photo.url(:aspect15small)) %>
<% end %> 

User Factory:

factory :user do 
  height 60
  weight 150
end

Pic Factory:

factory :pic do 
  photo { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec/photos/user1.jpg'))}
  user
  pic_order {generate(:pic_order)}
end

View Spec:

pics = build_stubbed_list(:pic, 10)
users = build_stubbed_list(:user, 10)
assign(:users, users)
render

Running the spec results in ActionView::Template::Error: undefined method `photo' for nil:NilClass . Obviously, the user does not have a pic associated with it.

I have tried numerous methods of creating the association in the spec, but have yet to be successful.

You can create associated objects in factory it self. try this

factory :user do 
  height 60
  weight 150

  after(:build) do |user|
   if user.pics.empty?
     user.pics.push build(:pic), build(:pic)
   end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM