I'm writing model tests with RSpec for a Cookbook model. Each user has_many cookbooks, and each cookbook belongs_to a user. To make sure that a Cookbook could not be created without a user, I wrote the following test:
it "is invalid without a user" do
expect(FactoryGirl.build(:cookbook, user: nil)).to be_invalid
end
However, when running rspec, I get the following output:
1) Cookbook is invalid without a user
Failure/Error: expect(FactoryGirl.build(:cookbook, user: nil)).to be_invalid
NoMethodError:
undefined method `cookbooks' for nil:NilClass
So, then, to test for an error being raised, I made the test like this:
it "is invalid without a user" do
expect{FactoryGirl.build(:cookbook, user: nil)}.to raise_error(NoMethodError)
end
However, that test also fails with the following output:
1) Cookbook is invalid without a user
Failure/Error: expect{FactoryGirl.build(:cookbook, user: nil)}.to raise_error(NoMethodError)
expected NoMethodError but nothing was raised
If it means anything, here is the factory for the cookbook:
require 'faker'
FactoryGirl.define do
factory :cookbook do |f|
f.title "#{Faker::Name.first_name}'s recipes"
f.description "#{Faker::Name.last_name}'s favorite recipes."
f.user 1
end
end
How should I go about writing the model test so that it makes sure a user is required when creating a Cookbook?