I wanted to remove the FactoryGirl.build(:user)
everytime I want to create a user and so I added these lines:
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end
to the spec_helper.rb
. But this creates the following error:
`method_missing': `build` is not available on an example group (e.g. a `describe` or `context` block). It is only available from within individual examples (e.g. `it` blocks) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). (RSpec::Core::ExampleGroup::WrongScopeError)
Then I removed all the context/describe blocks, but that didn't change anything. Have any of you had the same problem with this and how may I fix it?
Currently my tests look like so:
require 'rails_helper'
RSpec.describe User, type: :model do
user = build(:user)
project = build(:project)
it "is valid with a firstname, lastname, email and password" do
expect(user).to be_valid
end
it "is invalid without a firstname" do
user = build(:user, name: nil)
expect(user.valid?).to be_falsey
expect(user.errors[:name].size).to eq(1)
end
it "is invalid without a lastname" do
user = build(:user, surname: nil)
expect(user.valid?).to be_falsey
expect(user.errors[:surname].size).to eq(1)
end
it "destroys dependent projects" do
user = User.create!(name: 'john', surname: 'doe', email: 't@example.com', password: 'password', password_confirmation: 'password')
user.projects << project
expect{user.destroy}.to change {Project.count}.by(-1)
end
end
Instead of:
user = build(:user)
project = build(:project)
Do:
let(:user) { build(:user) }
let(:project) { build(:project) }
In general it is not a good idea to define external variables to use them in a test, as this might make your tests order-dependent and extremely hard to debug. Always use the let
syntax, so the values are reinitialized for every test.