ruby on rails 4 - RSpec undefined method `full_name' for nil:NilClass -
i'm trying test following rspec , factorygirl:
describe 'get #show' "assigns requested dish @dishes" dish = create(:dish) :show, id: dish expect(assigns(:dish)).to eq dish end end
factorygirl.define factory :dish, :class => 'dish' |f| f.name "testdish" f.header "testheader" f.author_id "1" f.avatar { file.open("spec/support/sample_photo.jpg")} end factory :invalid_dish |f| f.name nil end end
but getting following error:
1) dishescontroller #show assigns requested dish @dishes failure/error: :show, id: dish actionview::template::error: undefined method `full_name' nil:nilclass # ./app/views/dishes/show.html.erb:3:in `_app_views_dishes_show_html_erb___4424609358762382481_2199208220' # ./app/controllers/dishes_controller.rb:16:in `block (2 levels) in show' # ./app/controllers/dishes_controller.rb:15:in `show' # ./spec/controllers/dishes_controller_spec.rb:14:in `block (3 levels) in <top (required)>'
i believe problems lies in show view line:
<p><%= @dish.author.full_name %></p>
in author.rb model i've defined following:
def full_name full_name = first_name + " " + last_name end
my dish.rb model belongs_to :author
, author.rb model has_many :dishes
i've tried google bit around, can't seem find specific answer issue, apart thread rspec: actionview::template::error: undefined method `full_name' nil:nilclass don't understand what's going on there.
let me know if more info needed!
thanks in advance chris
you undefined method 'full_name' nil:nilclass
error because in @dish.author.full_name
, @dish.author
nil i.e., dish record doesn't have matching author record.
what need setup factories such when create dish associated record gets created :
factorygirl.define factory :dish, :class => 'dish' |f| f.name "testdish" f.header "testheader" f.avatar { file.open("spec/support/sample_photo.jpg")} ## f.author_id "1" remove line association :author, factory: :assoc_author ## set association end factory :assoc_author, :class => 'author' |f| ## assign fields f.first_name "john" f.last_name "doe" end ## ... end
this way when call create(:dish)
, create record in dishes
table plus associated record in authors
table.
Comments
Post a Comment