无法访问“it”rails rspec测试类中的数据

时间:2015-09-28 13:36:53

标签: ruby ruby-on-rails-4 rspec-rails

当我们尝试执行以下代码时,我们无法访问newAccount方法中的数据also not able to search date in active recordsit

代码提取:

describe "search with name" do
                before :each do
                    newAccount = Account.new
                    newAccount.firstname = "涯噘暮"
                    newAccount.id = "405"
                    newAccount.save
                    data  = Account.execute_sql(['Select * from account where sfid= ? ','1'])
                    puts "Debug : #{data.to_json}"
                    newAccount = Account.new
                    newAccount.firstname = "涯 噘 暮"
                    newAccount.id = "2"
                    newAccount.save
                end
                it "should return direct matches during search" do
                    puts "#{newAccount}"
                    puts "#{Account.find_by_id(405)}"
                end
end

gem lib的详细信息:这些是我们用于测试的库。

gem 'rspec-rails', '2.5.0'
gem 'faker'
gem 'capybara'
gem 'guard-rspec'
gem 'launchy'
gem 'simplecov', :require => false
gem 'resque_spec'

1 个答案:

答案 0 :(得分:1)

这里有2个错误:

  1. Ruby中的变量名称区分大小写,因此var isMobile = ('ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/)); newaccount不同,请使用其中一个,最好Ruby style guide建议使用蛇案例(newAccount
  2. {li} new_account中的newAccount在任何before(:each)块中都不可见。将它们视为一个对象的不同方法,这样每个方法都有自己的局部变量,对于其他变量是不可见的。解决方案是使用实例变量,可以在一个对象的不同方法中共享。

    此代码应该有效:

    it

    您需要检查您的帐户是否真的已保存。你可以

    1. describe "search with name" do before :each do @newAccount = Account.new @newAccount.firstname = "涯噘暮" @newAccount.id = "405" @newAccount.save data = Account.execute_sql(['Select * from account where sfid= ? ','1']) puts "Debug : #{data.to_json}" @newAccount = Account.new @newAccount.firstname = "涯 噘 暮" @newAccount.id = "2" @newAccount.save end it "should return direct matches during search" do puts "#{@newAccount}" puts "#{Account.find_by_id(405)}" end end 之后添加p @newAccount.errors.full_messages,看看是否存在任何验证错误,导致您的模型无法保存。
    2. 使用@newAccount.save代替@newAccount.save!(请注意@newAccount.save字符)。如果您的保存不成功,这将抛出异常。