Search code examples
ruby-on-railsrspecfactory-botsorcery

Why does FactoryGirl(:build) work with Sorcery, but not FactoryGirl(:create)?


I'm trying to setup tests for my Rails app. I'm using Factory Girl and Rspec with Sorcery for authentication. For some reason this test doesn't pass:

describe "User" do
  it "has a valid the factory" do
    user = FactoryGirl.create(:user)
    user.should be_valid 
  end
end

But this one does:

describe "User" do
  it "has a valid the factory" do
    user = FactoryGirl.build(:user)
    user.should be_valid 
  end
end

The error on the failing test said that the password did not match its confirmation, so it seems like this has something to do with how Sorcery handles password encryption.

Has anyone else run into this issue? Does it have to do with how Sorcery encrypts the passwords? Is it intentional, or a bug?


Solution

  • build is valid because the built object really is a valid object, though existing in memory only.

    The create is not valid because save failed.

    The reason of saving failure, I think, should be about Activation. I don't have experience on Sorcery but Devise only, the principles are similar. It seems Sorcery ask for activation by default according to its README.

    It's easy to fix it directly in factory definition, by adding a hook of activation after creation.

    FactoryGirl.define do
      factory :user do
        # other fields
        after(:create) { |user| user.activate! }
      end
    end