Reputation: 3047
This isn't an issue, I just wanted to make sure that this code is having the effect for testing that I think it is having. I want to have a test that builds/creates the struct via the factory and check to make sure the changeset is valid, much like the default generated test. This way my factories are also tested for generating valid data.
For example, this default test which uses a map of attributes to create a struct changeset and validate the data:
@valid_attrs %{
email: "[email protected]",
first_name: "some content",
last_name: "some content",
password: "some content",
password_hash: "some content",
username: "some content",
mobile: "1112223333"}
@invalid_attrs %{}
test "changeset with valid attributes" do
changeset = User.changeset(%User{}, @valid_attrs)
assert changeset.valid?
end
Could it be rewritten with the factory like this?
test "changeset with ExMachina Factory attributes" do
user = build(:user)
changeset = User.changeset(user,%{})
assert changeset.valid?
end
As I'm learning Elixir, sometimes the semantics are confusing and I was hoping to get some clarification that this is the right direction to take. Is passing an empty map of attributes, because they are already defined in user
by the factory build(:user)
function validating the changeset correctly?
My next step would be to do something like I've done in Rails/Rspec/FactoryGirl where I have a FactorySpec which builds each of the models and validates that the model was built correctly. In this example, the factory spec builds each model and validates them.
#spec/models/factory.rb
FactoryGirl.factories.map(&:name).each do |factory_name|
describe "The #{factory_name} factory" do
it 'is valid' do
build(factory_name).should be_valid
end
end
end
#spec/models/post_spec.rb
require 'rails_helper'
RSpec.describe Post, type: :model do
end
#spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
end
Lastly, Is there any suggestions on how to create a spec/test in ExUnit that repeatable tests all the structs using their respective factories to validate their build/create
generation?
I have an issue (198) open in the ExMachina repo as well for cross reference.
Upvotes: 1
Views: 450
Reputation: 3047
The ExMachina
docs have a function titled params_for
which generate the attributes map. This way a test can be added in addition to the one created by the Phoneix scaffold model generators.
test "changeset with valid factory" do
changeset = User.changeset(%User{}, params_for(:user) )
assert changeset.valid?
end
Upvotes: 1