1

我一直在浏览 Rails 教程,将用户帐户放在一起并为我正在处理的项目运行测试。

Failures:

  1) when email format is invalid should be invalid
     Failure/Error: @user.email = invalid_address
     NoMethodError:
       undefined method `email=' for nil:NilClass
     # ./spec/models/user_spec.rb:71:in `block (3 levels) in <top (required)>'
     # ./spec/models/user_spec.rb:70:in `each'
     # ./spec/models/user_spec.rb:70:in `block (2 levels) in <top (required)>'

  2) when email format is valid should be valid
     Failure/Error: @user.email = valid_address
     NoMethodError:
       undefined method `email=' for nil:NilClass
     # ./spec/models/user_spec.rb:81:in `block (3 levels) in <top (required)>'
     # ./spec/models/user_spec.rb:80:in `each'
     # ./spec/models/user_spec.rb:80:in `block (2 levels) in <top (required)>'

Finished in 0.527 seconds
9 examples, 2 failures

Failed examples:

rspec ./spec/models/user_spec.rb:67 # when email format is invalid should be invalid
rspec ./spec/models/user_spec.rb:78 # when email format is valid should be valid

我不知道问题是什么。我看到了它的内容,但我什至 C&P 了教程中的代码,以仔细检查我所做的工作,以确保所有内容都正确输入。

这是 user_spec 文件。

https://gist.github.com/pwz2k/4770845

这是 user.rb 文件。

https://gist.github.com/pwz2k/4770854

直到我添加了电子邮件验证,失败才出现。

4

2 回答 2

0

确保在开始测试之前创建 @user .. 你的用户测试中有这些行吗?(rails教程清单6.16

before do
    @user = User.new(name: "Example User", email: "user@example.com")
end
于 2013-02-12T17:04:35.707 回答
0

错误很明显!您将电子邮件设置为 nil 类。这意味着您应该将电子邮件设置给我们所说的用户

 @user.email = "something"

错误是抱怨没有用户,并且不会有任何用户电子邮件。

To make is work here 是一个示例代码,可帮助您解决此问题。

 describe "validations" do
   before(:each) do
     @user = User.new(name: "gates", email: "somename@gmail.com")
   end
   it "should be invalid" do
     invalid_emails = %w{gs@gmail p.com name.gmail.com foo.ymail}
     invalid_emails.each do |invalid_email|
       @user.email = invalid_email
       expect(@user.email).to_not be_valid
    end
   end

   it "should be valid" do
    @user.name = "somename"
    valid_emails = %w{user@foo.COM A_US-ER@f.b.org frst.lst@foo.jp 
    a+b@baz.cn}
    valid_emails.each do |valid_email|
     @user.email = valid_email
     expect(@user.email).to be_valid
    end
   end  
 end

请确保您已在您的fixures 文件夹中为用户创建了一个fixture。

希望这可以帮助!

于 2015-01-28T06:10:39.463 回答