【问题标题】:Rails rspec factorygirl pluralize testRails rspec factorygirl复数测试
【发布时间】:2013-01-09 13:34:54
【问题描述】:

是否可以在 rspec 中测试复数功能?

let(:schedule) { FactoryGirl.create(:schedule) }

Failure/Error: it { should have_selector('h1', text: pluralize(Schedule.count.to_s, "schedule")) }
 NoMethodError:
   undefined method `pluralize' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0xb607068c>

回答:(正如下面 Eric C 所指出的)

describe SchedulesHelper do
  describe "pluralize schedule" do
    if(Schedule.count > 0)
        it { pluralize(1, "schedule").should == "1 schedule" }
    else
        it { pluralize(0, "schedule").should == "0 schedules" }
    end    
  end 
end

【问题讨论】:

  • 您似乎没有在测试复数方法。您似乎正在测试是否存在某些 html,并且您正在使用复数方法来帮助您。您是在问是否可以使用复数方法进行测试?
  • 是的。是否可以测试“复数”?

标签: ruby-on-rails-3.2 rspec2 factory-bot


【解决方案1】:

我是 RoR 和 RSpec 的新手,我遇到了与启动此线程的伙伴类似的错误:

失败:

 1) Static Pages Home Page for signed-in users should show the total feeds
 Failure/Error: expect(page).to have_content(pluralize(user.feed.count, 'micropost'))
 NoMethodError:
     undefined method `pluralize' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1::Nested_2:0x007fade8f35938>
     # ./spec/requests/static_pages_spec.rb:39:in `block (4 levels) in <top (required)>'

我尝试了view.pluralize,但没有运气......我终于在我的集成测试中使用了它:

it "should show the total feeds" do
    expect(page).to have_content("micropost".pluralize(user.feed.count))                  
end

我的测试运行良好。

希望这可以对其他人有所帮助。

iVieL.

【讨论】:

  • 谢谢!这对我帮助很大。我建议您可以通过针对特定元素expect(page).to have_selector("section span", text: "micropost".pluralize(user.feed.count)) 来改进它
【解决方案2】:

你的问题的答案是……有点。 Rails 提供了使用复数和使用 rspec-rails 的功能,假设这是您正在使用的,让您能够根据需要调用 rails 方法。如果这是一个视图测试,看起来有点像,你可以输入如下内容:

it { should have_selector('h1', text: view.pluralize(Schedule.count.to_s, "schedule")) }

这里的关键是您要在复数之前添加 view.

我想强调的是,在测试时,在看似视图测试的内部测试辅助方法并不是一个好主意。如果你真的想测试复数本身,最好在辅助规范中测试它。做类似的事情:

it { pluralize(1, "schedule").should == "1 schedule" }
it { pluralize(0, "schedule").should == "0 schedules" }

这样您就可以确定结果并在其他测试中做出假设,然后测试正确的结果。它实际上将不可避免地使测试变得更好,因为如果像复数这样的助手发生变化,那么你有两个测试会警告这种变化。然后,您可以进行相应的调整。只是一个想法。

【讨论】:

  • 好的。谢谢埃里克。我现在在我的助手规范中测试了复数。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
相关资源
最近更新 更多