I'm trying to write a simple test that validates the presence of an email
attribute defined as a sequence in the factory, but the assignment fails and the email
attribute retains its value.
I have a factory that uses a sequence to set the email attribute on a user:
FactoryBot.define do
factory :user do
first_name { 'John' }
last_name { 'Doe' }
sequence(:email) { |n| "#{first_name}.#{last_name}.#{n}@example.com".downcase }
password { 'password' }
end
end
I can't assign email
to a new value in my test:
require 'test_helper'
describe User do
subject { build :user }
it "must be a valid object" do
_(subject).must_be :valid?
end
it "requires an email address" do
subject.email = nil
_(subject).wont_be :valid?
end
end
Within the test, I expect the value of subject.email
to be nil
when the assertion is evaluated.
The value of subject.email
is still the value assigned by the factory upon build (e.g., [email protected]
) when the assertion is evaluated. In a pry session, I see something similar to this:
> subject.email
# "[email protected]"
> subject.email = nil
# nil
> subject.email
# "[email protected]"
factory_bot version: 5.1.2
rails version: 4.2.11.1
ruby version: 2.4.9
Hm, that doesn't ring any bells for me. Once the object is built, I can't think of any reason why factory_bot would affect how later attributes get assigned. Can you provide a reproduction script in this format: https://github.com/thoughtbot/factory_bot/blob/master/.github/REPRODUCTION_SCRIPT.rb
I'm going to close this for now, since it is not something I can reproduce. But we can reopen it if you are able to provide a reproduction script. Thank you!
Turns out someone overrode the writer method (def email=(value)
) that had a guard clause in it for empty?
values.
Most helpful comment
Turns out someone overrode the writer method (
def email=(value)
) that had a guard clause in it forempty?
values.