RSpec with devise

邮差的信 提交于 2019-12-14 03:04:34

问题


im new to rails :) im trying to run my first test. why does this test pass? username should have at least 2 characters, my username has more and it still passes test.

user.rb:

validates :username, :length => { :minimum => 2 }

user_spec.rb

require 'spec_helper'

describe User do

before do
  @user = User.new(username: "Example User", email: "user@example.com",
                   password: "foobar", password_confirmation: "foobar")
end

describe "when name is not present" do
  before { @user.username="aaaahfghg" }
  it { should_not be_valid }   end

end

回答1:


describe "when name is not present" do
 before {  @user.username = "aaaahfghg" }
 it { should_not be_valid }   
end

First, your describe block is testing for the wrong thing. If you would like to test for "name is not present" you should set:

@user.username = "" #makes the username empty.

However, in order to check if the username is empty you should add validates :username, presence: true . Although you might not need it since you have a { minimum: 2 } validation

Now, @user.username = "aaaahf" # a better way of writing it is 'a' * 5 for example, it create a string of 5 a's = aaaaa.

That says that your username is more than 2 characters so your validation is fine, { minimum: 2 } the test should pass.

If you want to make sure that usernames are more than 2 characters then

@user.username = 'a'

Hope that help.




回答2:


This line:

it { should_not be_valid }

Uses the implicit subject. RSpec automatically creates an instance of the class User that you can then use implicitly within an it block. But your test then creates another instance and assigns it to @user -- the two instances are not the same.

If you want to use the implicit subject, you can do:

subject { User.new(args) }
before {  subject.username = "aaaahfghg" }
it { should_not be_valid }   


来源:https://stackoverflow.com/questions/15209197/rspec-with-devise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!